JavaScript Reference

Essential JavaScript commands, methods, and concepts for beginners and web developers.

Variables

let

Creates a variable.

let age = 25;

const

Creates constant value.

const pi = 3.14;

var

Older variable method.

var name = "Sam";

typeof

Checks data type.

typeof "Hello"

Output & Input

console.log()

Prints to console.

console.log("Hello");

alert()

Popup message.

alert("Hi");

prompt()

Gets user input.

prompt("Enter name");

confirm()

True/false popup.

confirm("Continue?");

Strings

.length

String length.

"Hello".length

.toUpperCase()

Uppercase text.

"hello".toUpperCase()

.toLowerCase()

Lowercase text.

"HELLO".toLowerCase()

.includes()

Checks text exists.

"Hello".includes("H")

.slice()

Cuts part of string.

"Hello".slice(0,2)

Template Strings

Insert variables in text.

`Hello ${name}`

Math

+

Add numbers.

5 + 2

-

Subtract numbers.

10 - 3

*

Multiply numbers.

4 * 5

/

Divide numbers.

20 / 4

%

Remainder operator.

10 % 3

Math.random()

Random number.

Math.random()

Math.floor()

Rounds down.

Math.floor(4.9)

Conditions

if

Runs code if true.

if(age > 18){}

else

Runs alternative code.

else {}

else if

Checks another condition.

else if(age > 10){}

===

Checks equal value.

5 === 5

>

Greater than.

10 > 5

<

Less than.

2 < 5

Loops

for

Repeats code.

for(let i=0;i<5;i++){}

while

Loops while true.

while(x < 5){}

break

Stops loop.

break;

continue

Skips loop step.

continue;

Functions

function

Creates function.

function test(){}

return

Returns value.

return total;

Arrow Function

Short function syntax.

const add = () => {}

Parameters

Function inputs.

function add(a,b){}

Arrays

[]

Creates array.

let fruits = [];

.push()

Adds item.

fruits.push("Apple")

.pop()

Removes last item.

fruits.pop()

.length

Array size.

fruits.length

.forEach()

Loops through array.

fruits.forEach()

.map()

Transforms array.

numbers.map()

.filter()

Filters items.

numbers.filter()

Objects

{}

Creates object.

let user = {};

Object Property

Stores value.

user.name = "Sam"

Object.keys()

Gets object keys.

Object.keys(user)

DOM Manipulation

document.querySelector()

Selects element.

document.querySelector(".box")

document.getElementById()

Select by ID.

document.getElementById("box")

.innerHTML

Changes HTML content.

box.innerHTML = "Hi"

.textContent

Changes text.

box.textContent = "Hello"

.style

Changes CSS.

box.style.color = "red"

.classList.add()

Adds CSS class.

box.classList.add("active")

.classList.remove()

Removes class.

box.classList.remove("active")

Events

addEventListener()

Listens for events.

button.addEventListener()

click

Mouse click event.

"click"

keydown

Keyboard event.

"keydown"

submit

Form submit event.

"submit"

Timers

setTimeout()

Runs later.

setTimeout(test,1000)

setInterval()

Repeats timer.

setInterval(test,1000)

clearInterval()

Stops timer.

clearInterval(timer)