Skip to content
Shahad Mahmud
Go back

Basic JavaScript Notes

Edit page

Data types and variables

var vs let vs const

⌨️ Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.

⌨️ It is common to use UPPERCASE variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).

Operators

JS supports all basic kind of operators. Some of the operators are listed below:

OperatorPurposeExample
++increment by 1i++;
--decrement by 1i--;
+=Addition and assigna += 1
-=Subtraction and assigna -= 1
*=Multiply and assigna *= 8
/=Divide and assigna /= 4
\Escapes certain characters."he said, \"I love cricket\""
==Equality operator. Checks if two items are equal. Data type invariant.1 == 1 // true also 1 == '1' // true
===Strict equality, i.e. types of the comparing items must be same.1 === 1 // true but 1 === '1' // false
!= Inequality operator. true when two items are not equal.1 != 2 // true
!==Strict inequality operator.1 !== '1' // true
>Greater than operator. Not strict.4 > '2' // true
>=Greater than or equal operator. Not strict.4 >= '4' // true
<Less than operator. Not strict.1 < '2' // true
<=Less than or equal operator. Not strict.4 <= '4' // true
&&Logical and operator.
``
typeofReturns the type of a variable.typeof "Jon"
a ? b : cTernary operator.a > b ? "a is greater" : "b is greater"

📌 If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.

Type Coercion

In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another. This is known as Type Coercion.

1   ==  1  // true
5   ==  2  // false
4   == '4' // true
"3" ==  3  // true

String operations

let firstName = "Jon";
firstName[0] = "F";  // not permissable. [mutation]

firstName = "Fon"  // permissable. [reassignment]
let firstName = "Jon";
let lastName= "Doe";

let fullName = firstName + " " + lastName;  // string concatenation
console.log(fullName)
// >>> Jon Doe

Array

Array methods and properties

MethodPurposeExample
push()Adds one or more items to the end.arr.push(4, 5, 6);
pop()Removes and returns the last element.arr.pop()
shift()Removes and returns the first element.arr.shift()
unshift()Adds one or more items at the beginning.arr.unshift(1, 2, 3)
toString()Converts array to comma separated stringarr.toString()
lengthReturns the length of the arrayarr.length

Functions

function myAwesomeFunction (arg1, arg2) {
	// some awesome things here
	return SOMETHING;
}

Scopes

let myGlobal = 10;  // global

function func() {
	var myLocal = 100;  // local
  oopsGlobal = 5;  // global
}

Conditional statements

if/else statements

if (CONDITION) {
	// do something
} else if (ANOTHER CONDITION) {
	// do something else
} else {
	// do other things
}

switch statements

If we need to match one value against many options, we can use a switch statement. A switch statement compares the value to the case statements which define various possible values. Any valid JavaScript statements can be executed inside a case block and will run from the first matched case value until a break is encountered.

In a switch statement we may not be able to specify all possible values as case statements. Instead, we can add the default statement which will be executed if no matching case statements are found.

case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If the break is omitted, the next statement will be executed.

switch (VALUE) {
    case CONDITION:
        // do something
        break;
    case CONDITION:
        // do something else
        break;
    // ...
    default:
        // do another thing
        break;
}

Objects

object is a collection of key-value pairs, where the keys, often called properties, map to the value.

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  sayHello: function() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
  }
};

// Delete a property
delete object.property

Key characteristics:

Object methods

MethodPurposeExample
hasOwnProperty()Checks if object contains a property.object.hasOwnProperty(property);

Loops

while loop

while (CONDITION) {
    // do something
}

for loop

for(INITIALIZATION; CONDITION; FINAL_EXPRESSION) {
    // do something
}

do...while loop

do {
    // do something
} while (CONDITION);

Ternary Operator

CONDITION ? STATEMENT_IF_TRUE : STATEMENT_IF_FALSE

// example
// a < b ? "a is smaller" : "b is smaller";

Some methods

MethodDescriptionExample
Math.random()Returns a random number in range 0 (inclusive) to 1 (exclusive)
Math.floor()Rounds number down
parseInt(string, radix)Parses a string and returns an integer. radix indicates the base in which the string is written.parseInt("007", 10); // 7

Edit page
Share this post:

Previous Post
How to use multiple GitHub account using GitHub CLI
Next Post
62 - Unique Paths