---
# System prepended metadata

title: Note on Javascript

---

JavaScript is a text-based, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML and CSS.
 It was invented by Brendan Eich in 1995 to add interactivity to webpages.
 As a client-side scripting language, JavaScript executes on the user's computer, making it faster than server-side languages like PHP or ASP.
 It is one of the core technologies of the World Wide Web, used to create dynamically updating content, control multimedia, and animate images.
 
It is used for popular websites.

WHAT IS THE USE OF JAVASCRIPT?
Backend web development
Mobile app development
Desktop Development.

MINI Js PROJECTS
1. to-do-list 
2. Quiz App.
3. Notes app.
4. Weather app.
5. Calculator
6. image gallery.

Ways to ouptut in Javascript
1. document.write("")
2. console.log("")
3. alert("")

**Global vs Block Scope in JavaScript**
In JavaScript, global scope refers to variables that are accessible from anywhere in the code, including inside functions and blocks. Variables declared in the global scope are known as global variables and are accessible throughout the entire program.

Block scope, on the other hand, is a more restricted type of scope introduced in ES6 with the let and const keywords. Variables declared within a block (such as within curly braces {}) are only accessible within that block and any nested blocks. They are not accessible outside of the block in which they are defined.

if (true) {
  let blockVar = "I'm in a block";
  console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined

In this example, blockVar is accessible within the if block but not outside of it.

Global variables declared with var, let, or const can be accessed globally, whereas block-scoped variables declared with let or const are only accessible within their respective blocks.

**Function Scope vs Block Scope**
Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function.

Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop. To be consise the variables declared inside the curly braces are called as within block scope.

In JavaScript, function scope and block scope refer to the accessibility of variables within specific parts of the code.

Function scope means that variables declared within a function are only accessible within that function and any nested functions. Variables declared with the var keyword have function scope. For example, a variable declared inside a function cannot be accessed outside of that function.

Block scope refers to the accessibility of variables within a block of code, typically defined by curly braces {}. Variables and functions declared with let and const keywords have block scope. Variables declared inside a block are only accessible within that block and any nested blocks, not outside of it.

For instance, if a variable is declared with let or const within an if block, it will not be accessible outside of that block.

let x = 10;
console.log(x); // Outputs 10

In contrast, a variable declared with var within the same block would be accessible outside of the block because var declarations are function-scoped, not block-scoped.

let x = 10;
console.log(x); // Outputs 10

In a loop, let ensures that each iteration captures its own instance of the loop variable, avoiding the issue where the last value of the loop variable is captured by closures when using var

for (let i = 0; i < 5; i++) {
    setTimeout(() => console.log(i), 1000);
}
// Each setTimeout will log the correct value of i from 0 to 4

Using let also allows for variable reassignment within the same block scope.

let userCount = 30;
userCount = 31;
console.log(userCount); // Outputs 31

WHAT ARE VARIABLES?
JavaScript variables are named containers used for storing values, which can be any JavaScript data type, including numbers, strings, or objects. They allow you to store and manipulate data within a program. In JavaScript, variables can be declared using the var, let, or const keywords. The var keyword was used exclusively before ES2015, but let and const were introduced in ES2015 to provide better scoping and immutability options.

Variables declared with let or const are block-scoped, meaning they can only be accessed within the block they are declared in, whereas var is function-scoped and can be accessed outside the block even if it is within the same function.
 Variables declared with const cannot be reassigned a new value, making them useful for constants, while let and var allow reassignment.

It is considered good practice to declare variables before using them and to prefer let or const over var for better code maintenance and to avoid common pitfalls like hoisting and scope issues.

Variables in JavaScript must follow naming conventions, allowing the use of letters, numbers, underscores, and dollar signs, but they cannot start with a digit or contain hyphens.

To Store Values;
1. Var
2. Let.
3. Const.

**VAR**
In JavaScript, var is a keyword used to declare variables. It has been part of the language since its inception and can be used to declare function-scoped or globally-scoped variables.
 Variables declared with var can be re-declared or updated within their scope, and they are hoisted to the top of their containing scope, meaning they can be accessed before their declaration in the code.
 However, due to its peculiarities, such as function scope and lack of block scope, the use of var has become less common in modern JavaScript, and it's often recommended to use let or const for clearer scoping rules and better maintainability.
 
Once you declare a valuable, you attach value to it with =. you can reassign a value to it. the value name accepts on letter or symbol and not number.

It is case sensitive.

**LET**
Let keyword is used to declare a block scoped variable. This means that the variable is only visible within the block in which it is declared.

In JavaScript, the let keyword is used to declare a variable with block scope, meaning the variable is only accessible within the block (such as a loop or conditional statement) where it is declared. This contrasts with the var keyword, which has function scope and can lead to issues like variable hoisting and scope leakage.

The let keyword was introduced in ECMAScript 6 (ES6) and provides a safer way to declare variables, helping to avoid common pitfalls associated with var. It supports modern JavaScript best practices, including compatibility with modules, destructuring, and other ES6+ features.

A key feature of let is the Temporal Dead Zone (TDZ), which prevents accessing a let variable before it is declared, ensuring safer coding practices.

**CONST**
The const is used to decalare a constant variable.This means that it cannot be reassigned to a new value. 
In JavaScript, const is a keyword used to declare variables that cannot be reassigned once they are initialized, ensuring immutability of the variable binding
 [4]. However, if the variable is an object or an array, its properties or elements can still be modified
 [4]. Variables declared with const have block scope, meaning they are accessible only within the block, statement, or expression in which they are defined.
 Unlike let, const cannot be reassigned after initialization, and attempting to do so results in a TypeError.
 Additionally, variables declared with const are not hoisted to the top of the code, and accessing them before they are defined will cause an error.
 
**WHAT IS SCOPE IN JAVASCRIPT**
Scope refers to the visibility of variables and functions within a program.
Three Types of Scope:
1. Global Scope.
2. Function Scope.
3. Block Scope.

**GLOBAL SCOPE**
The Global scope is the uttermost scope in a javascript program. Variable and functions declared in the Global scope are visible from anywhere in the program.

In JavaScript, global scope refers to the outermost scope in a program where variables and functions are accessible from anywhere within the code, including inside functions, blocks, or nested scopes.
 Variables declared in the global scope are known as global variables and are accessible throughout the entire program.
 For example, a variable declared outside of any function or block is part of the global scope and can be accessed globally.

Using too many global variables can lead to name collisions, pollution of the global namespace, and security risks, so it is advisable to limit their use and prefer local variables whenever possible.

var x = "hello, LiteCoders"

function example(){
    console.log(x)
}

**FUNCTION SCOPE**
A function scope is created when a function is declared. Variables and Functions declared in a functions scope are only visible within that function.

Function Scope in JavaScript
In JavaScript, function scope refers to the accessibility of variables and functions that are defined within a function. Variables and functions declared with the var keyword have function scope, meaning they are accessible only within that function and any nested functions, but not outside of it.
 For example, if a variable is declared inside a function, it cannot be accessed before its declaration or outside of the function in which it is defined.
 This ensures that variables declared within a function do not interfere with variables outside the function, maintaining a clean and organized code structure.
 
 Example:

function exampleFunction() {
var x = 10; // Variable x has function scope
console.log(x); // Output: 10
function innerFunction() {
console.log(x); // Output: 10
}
innerFunction();
}
exampleFunction();
console.log(x); // Error: x is not defined

Example
function example(){
    var fs = "Hello, Litecoders";
    
    console.log(fs);
}

example();

console.log(fs);

**BLOCK SCOPE**
A block scope in Javascript refers to the visibility of variables and functions within a block of code.

A block of code is a group of statements that are enclosed in curly braces. ({})

Variable and functions declared in a blocks scope are only visible within that block.

Block scope in JavaScript refers to the scope of variables and functions that are defined within a block of code, such as within a pair of curly braces {}. Variables and functions declared with let and const keywords have block scope.
 Variables declared inside a block are only accessible within that block and any nested blocks, and are not accessible outside of the block in which they are defined.
 For example, a variable declared inside an if statement's block is only accessible within that block and cannot be accessed outside of it.
 
Example.

function example(){
    if(true){
        let bv = "Greatstack";
        console.log(bv);
    }
}
example()

**DATA TYPES IN JAVASCRIPT**
1. Primitive Data types
2. Reference Data types

1. Primitive Data types
such as;
a. String.
b. Number.
c. Boolean.
d. Null.
e. Undefined.
f. BigInt.
g. Symbol.

2. Reference Data types
such as;
a. Object.
b. Array.
c. Function.

**PRIMITIVE DATA TYPE**
**STRING**
In Javascript, a string is a sequence of zero or more characters.

A string starts and ends with either a single quote ('') or a double quote ("") or Backticks `Hello`

Javascript strings are for storing and manipulating text. 

example
let firstName = "Elon";
let lastName = 'Musk';

**NUMBER**
Number represents integer and floating-point numbers.
In JavaScript, numbers are used to represent numerical values, which can be whole numbers or decimal numbers. They are stored as double-precision 64-bit binary format IEEE 754 values, similar to the double type in Java or C#. This format allows for the representation of fractional values but has limits on the magnitude and precision of the stored number.

JavaScript numbers can also be expressed in various formats, including binary, octal, hexadecimal, and exponential notation. For example, binary numbers start with 0b or 0B, octal numbers with 0o or 0O, hexadecimal numbers with 0x or 0X, and exponential numbers follow the beN format where b is a base integer or float number, e is the exponent character, and N is the exponential power number.

The Number() function can convert values of other types to numbers, returning NaN if the value cannot be converted.

let num = 100;
console.log(num);

let x = "10";
console.log(typeof x);

**BOOLEAN**
This comes out true or false.

In JavaScript, a boolean represents one of two values: true or false.
 Booleans are used to represent truth values and are fundamental in decision-making and control flow within programming.
 They are often used in conditional statements, loops, and comparisons to control the flow of execution based on certain conditions.
 For example, a variable named "kitchenLights" set to "true" would indicate that the lights are on, and if it was set to "false", it would mean they are off.

example;
let learning = true;
let completed = false;

console.log(learing);

to check the type of data type, use typeof

example;
let x = 20>10;
console.log(x);

**UNDEFINED**
In JavaScript, undefined is a primitive value that represents a variable that has been declared but not yet assigned a value. It is also the default value of any variable or property that has not been assigned a value.

For example, if you declare a variable but do not assign it a value, it will be undefined:

let x;
console.log(x);  // Outputs: undefined
Additionally, when you try to access a property or an index of an array or object that does not exist, JavaScript returns undefined:

let user = {
    name: "John Doe",
    age: 14
};
console.log(user.hobby);  // Outputs: undefined
undefined is a global read-only property and should not be overridden to avoid making your code difficult to maintain and debug.

To check if a variable is undefined, you can use the typeof operator or direct comparison with undefined:

let myVar;
if (typeof myVar === "undefined") {
    console.log("myVar is undefined");
} else {
    console.log("myVar is defined");
}
Using the strict equality operator (===) is recommended when checking for undefined because null is not equivalent to undefined.

The void operator can also be used to obtain the undefined primitive value:

console.log(void 0);  // Outputs: undefined
Understanding undefined is crucial for writing reliable and bug-free JavaScript code, especially when handling optional function parameters or checking if an object property exists before accessing it.

**NULL**
In the Javascript, null is a special value that represents empty or unknown value.

In JavaScript, null is a primitive value that represents the intentional absence of any object value. It indicates that a variable points to no object and is often used to denote an empty or unknown value.

When checking for null, it is important to use the strict equality operator (===) to avoid type coercion, which can lead to unexpected results when using the loose equality operator (==). For example, null == undefined returns true due to type coercion, but null === undefined returns false because they are distinct values.

The typeof operator returns "object" for null, which is considered a bug but cannot be fixed due to compatibility issues with existing scripts.

Example Usage: null can be assigned to a variable to indicate that it is intentionally empty or undefined at the moment.

let number = null; // The number variable is empty and may have a value later.

**REFERENCE DATA TYPES**
**OBJECT**
In javascript, an object is a collection of properties, where each property is defined as a key value object.

In JavaScript, an object is a collection of key-value pairs, where each key is a string and each value can be any data type, including functions, which are known as methods.
 Objects can store multiple values and are often compared to real-life entities, such as a cup with properties like color and material.
 Each key-value pair in an object is referred to as a property, and these properties can be accessed using dot notation or bracket notation
 
EXAMPLE:
let person = {
    firstName: "Elone",
    lastName: "Musk",
    age:35
};

console.log(person);
console.log(typeof person);

**ARRAY**
An Sarray are a type of object that stores a collection of values.
In JavaScript, an array is an ordered list of values where each value is called an element and has a numeric position in the array known as its index. Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
 Arrays can be created using array literals, which involve using square brackets [] to define and initialize the array, or by invoking the Array constructor function.
 Arrays in JavaScript are objects, and elements are stored by reference, so when an array is assigned to another variable, both variables point to the same array in memory.
 
 example;
let newnum = [1,2,3,4,5,6];

console.log(newnum);
console.log(typeof newnum);

**FUNCTION**
In JavaScript, a function is a block of reusable code designed to perform a specific task. Functions can take inputs, known as parameters, and return outputs, called return values.
 They can be defined using the function keyword and invoked by their name followed by parentheses.
 Functions allow you to organize, reuse, and modularize code, making it more manageable and easier to understand. 
 
**OPERATORS IN JAVASCRIPT**
JavaScript Operators
In JavaScript, operators are special symbols used to perform operations on operands, which can be values or variables. They allow you to manipulate data and perform computations.
 There are various types of operators in JavaScript, including arithmetic, assignment, comparison, logical, bitwise, and more.
 Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
 Comparison operators are used to compare two values and return a boolean value (true or false).
 Logical operators are used to combine multiple Boolean expressions.
 Bitwise operators perform bit-level operations on numbers
 
 JavaScript Operators
JavaScript operators are special symbols used to perform operations on operands, which can be values or variables. They allow you to manipulate data and perform computations. There are several types of JavaScript operators, including; 
1. arithmetic operators, 
2. assignment operators, 
3. comparison operators, 
4. logical operators, 
5. bitwise operators, and 
6. String operators.

**ARITHMETIC OPERATORS**
Arithmetic operators in JavaScript are symbols used to perform basic mathematical operations like addition, subtraction, multiplication, division, and more on numeric values (operands).
 These operators include the addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--) operators.
 Arithmetic operators can also be used for other operations, such as string concatenation with the addition operator (+).
 
 Operator	Description
+	Addition
example
let sum = 5+3;
console.log(sum)

-	Subtraction
example
let minus = 5-3;
console.log(minus)

*	Multiplication
example
let mul = 5 * 3;
console.log(mul)

**	Exponentiation (ES2016)
example
let exp = 2**4;
console.log(exp)

/	Division
example
let div = 5 / 3;
console.log(div)

%	Modulus (Remainder)
example
let mod = 17 % 4;
console.log(mod)

++	Increment
--	Decrement


Operator	Name	       Description
+	        Addition	   Adds two operands
-	        Subtraction	   Subtracts the second operand from the first
*	        Multiplication Multiply both operands
/	        Division	   Divide the numerator by the denominator
%	        Modulus	       Outputs the remainder of an integer division
++	Increment	Increases an integer value by one
--	Decrement	Decreases an integer value by one

**assignment operators**
In JavaScript, assignment operators are used to assign values to variables. The simplest assignment operator is the equal sign (=), which assigns the value of its right operand to its left operand. For example, x = y assigns the value of y to x.

JavaScript also includes compound assignment operators that combine arithmetic operations with assignment. These include +=, -=, *=, /=, %=, and **=. For instance, x += y is equivalent to x = x + y, which adds the value of y to x and assigns the result back to x.

Operator	Example	Same As
=	        x = y	x = y
+=	        x += y	x = x + y
-=	        x -= y	x = x - y
*=	        x *= y	x = x * y
/=	        x /= y	x = x / y
%=	        x %= y	x = x % y
**=	x **= y	x = x ** y

example;
1. 
let ab = 5;

ab += 3;
console.log(ab);

2.
let cy = 5;
cy *= 4;

console.log(cy);

3.
let b = 5;
b -= 3;

console.log(b)

4.
let c = 10;
c *= 5;

console.log(c)

**INCREMENT AND DECREMENT OPERATORS**
The increment and decrement operators are used to increase or decrease the value of a variable by 1.
Increment and decrement operators in JavaScript are unary operators used to increase or decrease the value of a variable by one. The increment operator (++) increases the value of a variable by one, while the decrement operator (--) decreases the value of a variable by one. These operators can be used in two forms: postfix and prefix. When used in postfix form, the operator is placed after the operand (e.g., number++), and the value is returned before the increment or decrement. When used in prefix form, the operator is placed before the operand (e.g., ++number), and the value is returned after the increment or decrement.

The Increment operator is ++
The Decrement operator is --

The increment and decrement can be used in two ways;
Prefix and Postfix

**PREFIX**
Example;

let e = 10;

console.log(++a);
console.log(a);
 
let f = 10;
console.log(--a);
console.log(a);


**POSTFIX**

let t = 50;

console.log(a++);
console.log(a);


let s = 50;

console.log(s--);
console.log(s);

**COMPARISON OPERATORS**
Comparison operators compare two values and give back a bolean value: either true or False.

Comparison operators in JavaScript are used to compare two values and return a boolean value based on the comparison result. These operators can be used to check for equality, inequality, and relational comparisons like greater than, less than, and their respective or equal counterparts.

The == operator checks if the operands are equal, performing type conversion if necessary.
The === operator checks if the operands are equal and of the same type.
The != operator checks if the operands are not equal, performing type conversion if necessary.
The !== operator checks if the operands are not equal and/or not of the same type.
The > operator checks if the left operand is greater than the right operand.
The < operator checks if the left operand is less than the right operand.
The >= operator checks if the left operand is greater than or equal to the right operand.
The <= operator checks if the left operand is less than or equal to the right operand

< (Less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)

==(equal checks)
!= (inequality) (not equal) (flipped value of equal checks)

===(strict equality checks) (checks the Data type)

!== (strict inequality) (flipped value strict equality checks)

example;
let g = 10;
let h = 20;

console.log(g < h);
console.log(g > h);
console.log(g <= h);
console.log(g >= h);

console.log(g == h);
console.log(g != h);

console.log(g === h);
console.log(g !== h);

**LOGICAL OPERATORS**
Logical operators perform logical operations like;

AND (&&)
OR (!!)
NOT (!)

Logical operators in JavaScript are used to determine the logic between variables or values. There are three main logical operators:

AND (&&): This operator accepts multiple arguments and evaluates the operands from left to right. If the result is false, it stops and returns the original value of that operand. Otherwise, if all operands are truthy, it returns the last truthy value. For example, expression1 && expression2 is true only if both expression1 and expression2 are true.

SAMPLE:
Evaluates operands and return true only if all are true.

true && true; // true
true && false; // false
false && true; // false
false && false; // false

EXAMPLE;

let g = 10;
let h = 20;

console.log(x > 0 && y > 0);
console.log(x > 0 && y < 0);
console.log(x < 0 && y > 0);
console.log(x < 0 && y < 0);


OR (||): This operator returns true if either expression1 or expression2 is true. It also evaluates operands from left to right and stops if it finds a true value. For instance, expression1 || expression2 returns true if either expression1 or expression2 is true.

SAMPLE:
returns true even if one of the multiple operands is true.

true || true; // true
true || false; // true
false || true; // true
false || false; // false

EXAMPLE;


let x = 10;
let y = 20;

console.log(x > 0 || y > 0);
console.log(x > 0 || y < 0);
console.log(x < 0 || y > 0);
console.log(x < 0 || y < 0);


NOT (!): This operator converts the operand to a boolean and returns the flipped value. If the operand is true, it returns false, and if the operand is false, it returns true. For example, !expression returns false if expression is true and vice versa.

SAMPLE;
Converts operator to boolean and returns flipped value;



console.log(!Yes);
console.log(!No);

These operators are commonly used to make decisions based on conditions specified for statements, manipulate boolean values, and set termination conditions for loops.

**STRING OPERATORS**
In javascript, you can also use the + operator to concatenate (join) two or more strings.

JavaScript string operators are used to manipulate and perform operations on strings. There are two primary string operators:

Concatenate Operator (+): This operator joins two strings together. For example, "str1" + "str2" results in "str1str2".
Concatenate Assignment Operator (+=): This operator appends a string to the end of another string and assigns the result back to the original variable. For example, str += "str2" appends "str2" to str.

Example;
console.log("hello " + "World");

let a = 'Javascript';
a += ' tutorial';

console.log(a);

**OPERATOR PRECEDENCE**
Operator precedence in Javascript determines the order in which operators are parsed concerning each other.


![Screenshot from 2025-03-04 11-39-23](https://hackmd.io/_uploads/ByvhYUNskl.png)


In JavaScript, operator precedence determines the order in which operations are performed in an expression. For example, multiplication has a higher precedence than addition, meaning that in an expression like 10 + 5 * 2, the multiplication is evaluated first, resulting in x = 20.

Parentheses can be used to alter the default precedence, ensuring that operations within parentheses are calculated first. For instance, in the expression (10 + 5) * 2, the addition inside the parentheses is performed first, resulting in x = 30.

When operations have the same precedence, such as addition and subtraction, they are calculated from left to right. In the expression 10 - 5 + 3, the subtraction is performed first, followed by the addition, resulting in x = 8.

JavaScript follows the same operational order as traditional mathematics, ensuring consistency in how expressions are evaluated.

EXAMPLE;
let results = 2 + 3 * 4;
// Expected output: 14

console.log(3 + 4 * 5); // 3 + 20
// Expected output: 23

console.log(4 * 3 ** 2); // 4 * 9
// Expected output: 36

let a;
let b;

console.log((a = b = 5));
// Expected output: 5


**OPERATOR ASSOCIATIVITY**
Operator associativity in Javascript defines the order in which operators of the same precedence are evaluated.

Types;
Left to right
right to left

![Screenshot from 2025-03-04 11-45-40](https://hackmd.io/_uploads/B1h-qLEoyl.png)

let result = 4 - 2 -1;
