• Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
MYTAT
  • Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
JavaScript
  • JavaScript Introduction
  • JavaScript Where To
  • JavaScript Output
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Comments
  • JavaScript Variables
  • JavaScript Let
  • JavaScript Const
  • JavaScript Operators
  • JavaScript Assignment
  • JavaScript Data Types
  • JavaScript Functions
  • JavaScript Objects
  • JavaScript Events
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript Numbers
  • JavaScript Number Methods
  • JavaScript Arrays
  • JavaScript Array Const
  • JavaScript Array Methods
  • JavaScript Sorting Arrays
  • JavaScript Array Iteration
  • JavaScript Date Objects
  • JavaScript Date Formats
  • JavaScript Get Date Methods
  • JavaScript Set Date Methods
  • JavaScript Math Object
  • JavaScript Random
  • JavaScript Booleans
  • JavaScript Comparison And Logical Operators
  • JavaScript If Else And Else If
  • JavaScript Switch Statement
  • JavaScript For Loop
  • JavaScript Break And Continue
  • JavaScript Type Conversion
  • JavaScript Bitwise Operations
  • JavaScript Regular Expressions
  • JavaScript Errors
  • JavaScript Scope
  • JavaScript Hoisting
  • JavaScript Use Strict
  • The JavaScript This Keyword
  • JavaScript Arrow Function
  • JavaScript Classes
  • JavaScript JSON
  • JavaScript Debugging
  • JavaScript Style Guide
  • JavaScript Common Mistakes
  • JavaScript Performance
  • JavaScript Reserved Words
  • JavaScript Versions
  • JavaScript History
  • JavaScript Forms
  • JavaScript Validation API
  • JavaScript Objects
  • JavaScript Object Properties
  • JavaScript Function Definitions
  • JavaScript Function Parameters
  • JavaScript Function Invocation
  • JavaScript Closures
  • JavaScript Classes
  • Java Script Async
  • JavaScript HTML DOM
  • The Browser Object Model
  • JS Ajax
  • JavaScript JSON
  • JavaScript Web APIs
  • JS Vs JQuery
  • Home
  • Courses
  • JavaScript
  • JavaScript Variables

JavaScript Variables

Previous Next

JavaScript Variables

In JavaScript, variables are used to store and manipulate data. They act as containers for storing values such as numbers, strings, objects, or functions. Variables play a crucial role in programming as they allow developers to work with dynamic data and perform operations on that data.


Variable Declaration and Initialization

In JavaScript, variables are declared using the var, let, or const keywords. Here's a brief explanation of each:
 

  • var: Historically used for variable declaration but has some scoping issues. Not commonly used in modern JavaScript.
  • let: Introduced in ES6 (ECMAScript 2015) and is block-scoped, meaning it is limited to the block (enclosed within {}) where it is declared.
  • const: Also introduced in ES6 and is used for declaring constants whose values cannot be reassigned once initialized. It is also block-scoped.


Let's see some examples:

 
var x; // Declaration of a variable using var
let y = 10; // Declaration and initialization of a variable using let
const PI = 3.14; // Declaration and initialization of a constant using const



Data Types in JavaScript Variables

JavaScript is a dynamically typed language, which means that variables can hold values of different types without explicitly specifying the type. Some common data types in JavaScript include:
 

  • Numbers: Represents numeric values, e.g., 10, 3.14.
  • Strings: Represents textual data enclosed within single ' or double " quotes, e.g., 'Hello', "JavaScript".
  • Booleans: Represents true or false values, e.g., true, false.
  • Objects: Represents complex data structures, e.g., {} (object literal), new Date() (date object).
  • Arrays: Represents ordered collections of elements, e.g., ['apple', 'banana', 'cherry'].
  • Functions: Represents reusable blocks of code, e.g., function add(a, b) { return a + b; }.


Variable Naming Rules

When naming variables in JavaScript, there are certain rules to follow:

  • Variable names can contain letters, digits, underscores _, and dollar signs $.
  • Variable names must start with a letter, underscore _, or dollar sign $. They cannot start with a digit.
  • Variable names are case-sensitive (myVariable is different from myvariable).
  • JavaScript reserves certain words (keywords) that cannot be used as variable names, such as if, else, function, etc.


Examples of JavaScript Variables

Let's look at some examples to understand how variables are used in JavaScript:


Example 1: Numeric Variables
 

let num1 = 10;
let num2 = 5;
let sum = num1 + num2;
console.log(sum); // Output: 15
In this example, num1 and num2 are numeric variables, and sum stores the result of adding num1 and num2.
 

Example 2: String Variables

 
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName;
console.log(fullName); // Output: John Doe

Here, firstName and lastName are string variables, and fullName stores their concatenated value.


Example 3: Boolean Variables
 

let isLogged = true;
if (isLogged) {
  console.log('User is logged in.');
} else {
  console.log('User is not logged in.');
}
 
 

The isLogged variable is a boolean variable that determines if a user is logged in or not.


Example 4: Array Variables
 
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Output: apple

In this example, fruits is an array variable that stores a list of fruits.


Example 5: Object Variables

 

let person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};
console.log(person.firstName); // Output: John

The person variable is an object variable that stores information about a person.



Example 6: Constant Variables

 

const PI = 3.14;
let radius = 5;
let area = PI * radius * radius;
console.log(area); // Output: 78.5

In this example, PI is a constant variable storing the value of π (pi), which remains constant throughout the program.



Scope of Variables

Variables in JavaScript have different scopes based on how and where they are declared:

Global Scope: Variables declared outside of any function have global scope and can be accessed throughout the program.

 
let globalVar = 'I am global';

function myFunction() {
  console.log(globalVar); // Output: I am global
}


myFunction();

Function Scope: Variables declared inside a function have function scope and can only be accessed within that function.
 


function myFunction() {
  let localVar = 'I am local';
  console.log(localVar); // Output: I am local
}
 


myFunction();

console.log(localVar); // Throws ReferenceError: localVar is not defined
Block Scope (let and const): Variables declared using let and const have block scope, which means they are limited to the block in which they are declared (e.g., inside {}).
 


if (true) {
  let blockVar = 'I am in block';
  console.log(blockVar); // Output: I am in block
}

console.log(blockVar); // Throws ReferenceError: blockVar is not defined
 

 



Practice Excercise Practice now

Using Let And Const (ES6)


let and const in JavaScript (ES6)

JavaScript ES6 (ECMAScript 2015) introduced two new keywords for declaring variables: let and const. These keywords provide better variable scoping and immutability, respectively, compared to the older var keyword. Understanding when and how to use let and const is crucial for writing modern and efficient JavaScript code.


Using let for Block-Scoped Variables

The let keyword allows you to declare block-scoped variables, meaning they are limited to the block ({}) in which they are defined. This is different from var, which has function scope or global scope, depending on where it's declared.

 

{
  let x = 10; // x is block-scoped to this block
  console.log(x); // Output: 10
}
console.log(x); // Throws ReferenceError: x is not defined
In this example, x is scoped only within the curly braces {} and cannot be accessed outside that block. This helps prevent variable conflicts and makes code more maintainable.



Using let for Loop Variables

One common use case of let is in loops, where each iteration should have its own separate variable. Using var in loops can lead to unexpected behavior due to variable hoisting.

 


for (let i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i); // Outputs 0, 1, 2, 3, 4 (each value after 1 second)
  }, 1000 * i);
}

In this loop, each iteration creates a new block-scoped i variable, ensuring that the correct value of i is logged after each timeout.


Using const for Constants

The const keyword is used to declare constants, which are variables whose values cannot be reassigned after initialization. This ensures immutability and prevents accidental changes to critical values.

 

const PI = 3.14;
PI = 3.14159; // Throws TypeError: Assignment to constant variable.

Attempting to reassign a value to a constant variable results in a TypeError. Constants are typically used for values that should remain unchanged throughout the program.


Using const with Objects and Arrays

While const prevents reassignment of the variable itself, it does not make objects or arrays immutable. You can still modify the properties of an object or the elements of an array declared with const.

 


const person = { name: 'John', age: 30 };
person.age = 40; // Valid, modifies the age property
person.address = '123 Main St'; // Valid, adds a new property
 



Similarly, with arrays:
 

const numbers = [1, 2, 3];
numbers.push(4); // Valid, adds an element to the array
numbers[0] = 0; // Valid, modifies the first element


Differences between let and const
 

  • Reassignment: Variables declared with let can be reassigned new values, while variables declared with const cannot be reassigned after initialization.
  • Block Scope: Both let and const have block scope, but const adds immutability within that scope.
  • Hoisting: Variables declared with let and const are not hoisted to the top of their block, unlike var.


When to Use let vs const

Use let for variables that will be reassigned or have limited scope within a block.
Use const for constants and variables that should not be reassigned after initialization.

 

let counter = 0; // Use let for variables that can change
const MAX_VALUE = 100; // Use const for constants


Common Mistakes with let and const
 

  • Not Initializing const: Constants declared with const must be initialized with a value; otherwise, it will result in an error.
  • Mutating Constants: While you can modify properties of objects and elements of arrays declared with const, you cannot reassign them entirely.

 


const greeting; // Error: Missing initializer in const declaration
const person = { name: 'John' };
person = { name: 'Jane' }; // Error: Assignment to constant variable
 

 



Practice Excercise Practice now

Much Like Algebra

Similarities between JavaScript Variables and Algebraic Variables

Symbolic Representation:

 

Algebra: In algebra, variables are represented using symbols such as 
????
x, 
????
y, or any other letter.
 

JavaScript: Similarly, in JavaScript, variables are symbolic representations that hold values, and you can use identifiers like x, y, z, or any meaningful name.


Value Assignment:
 
  • Algebra: In algebra, variables are assigned values to solve equations or represent unknown quantities.
  • JavaScript: In JavaScript, variables are used to store and manipulate data values within a program. For example:
 

let x = 5; // Assigning the value 5 to the variable x
const y = 10; // Assigning the value 10 to the constant variable y
 



Dynamic Nature:

Algebra: Variables in algebra can represent varying quantities, and their values can change based on equations or conditions.
JavaScript: Similarly, JavaScript variables declared with let can change their values during program execution, making them dynamic.

 

let age = 25;
age = 30; // Variable age changed from 25 to 30
 



Immutable Constants:

Algebra: Constants in algebra are values that remain unchanged throughout an equation or problem.
JavaScript: JavaScript const variables behave similarly to algebraic constants; once initialized, their values cannot be reassigned.

 

const PI = 3.14159; // Declaring a constant variable PI
// PI = 3; // Error: Cannot reassign a constant variable
 


Equations and Expressions:
  • Algebra: In algebra, variables are used in equations and expressions to represent relationships between quantities.
  • JavaScript: JavaScript variables are used in expressions and calculations, allowing for dynamic computations.
 
let a = 5;
let b = 10;
let sum = a + b; // Using variables in an expression


Examples

Algebraic Example:
 
Consider the equation 
????
=
2
????
+
3
y=2x+3, where 
????
x is a variable representing an unknown value. We can solve for 
????
y when 
????
=
5
x=5.

????
=
2
(
5
)
+
3
y=2(5)+3
????
=
10
+
3
y=10+3
????
=
13
y=13

Here, 
????
x represents a changing quantity, and the equation defines a relationship between 
????
x and 
????
y.


JavaScript Example:

In JavaScript, let's use variables to calculate the area of a rectangle given its length and width.

 

let length = 10; // Length of the rectangle
let width = 5; // Width of the rectangle

const area = length * width; // Calculating the area using variables
 
 
  • console.log("The area of the rectangle is: " + area); // Output: The area of the rectangle is: 50
  • In this example, length and width act as variables representing the dimensions of the rectangle, similar to how algebraic variables represent quantities.a

 



Practice Excercise Practice now

JavaScript Identifiers

JavaScript Identifiers

In JavaScript, an identifier is a name used to identify variables, functions, objects, arrays, or any other user-defined data structure. Identifiers are fundamental to the language, providing the means to label and refer to data. Understanding the rules and conventions for naming identifiers is essential for writing clear, maintainable code.


Rules for Identifiers

Starting Characters:

Identifiers must start with a letter (a-z or A-Z), a dollar sign ($), or an underscore (_).
They cannot start with a number (0-9).



Subsequent Characters:

After the first character, identifiers can include letters, digits (0-9), dollar signs, or underscores.

Case Sensitivity:

Identifiers in JavaScript are case-sensitive. For example, variable, Variable, and VARIABLE are three distinct identifiers.

Reserved Words:

Identifiers cannot be the same as reserved words. Reserved words are part of the JavaScript language syntax, such as break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, import, in, instanceof, let, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, and yield.

Best Practices for Identifiers

Descriptive Names:

Use meaningful names that describe the purpose of the variable. For example, totalAmount is more descriptive than x.

Camel Case Convention:

JavaScript developers often use camel case for identifiers. Camel case starts with a lowercase letter and uses uppercase letters to distinguish new words. For example, firstName or totalAmount.

Avoid Single Character Names:

Unless used in loops (e.g., i for index), avoid single character names as they lack context and clarity.

Use Constants for Immutable Values:

For values that do not change, use const and name the identifier in all uppercase with underscores separating words, such as MAX_LENGTH.

Consistent Naming Conventions:

Stick to a consistent naming convention throughout the codebase to enhance readability and maintainability.

Examples

Let's look at some examples of valid and invalid identifiers in JavaScript.


Valid Identifiers:
 


let myVariable;
const $element = document.getElementById("myId");
let _privateVariable;
const MAX_COUNT = 100;
let firstName = "John";
 



Invalid Identifiers:
 


// let 1stName; // Invalid: Starts with a number
// const new = "hello"; // Invalid: 'new' is a reserved word
 



Example: Using Identifiers in Code

Here is a practical example demonstrating how to declare and use variables, functions, and constants with proper identifiers.

 


// Constants
const MAX_USERS = 1000;
const API_URL = "https://api.example.com";

// Variables
let userCount = 0;
let userName = "Alice";

// Function
function incrementUserCount() {
    if (userCount < MAX_USERS) {
        userCount++;
        console.log(`User count increased to: ${userCount}`);
    } else {
        console.log("Max user limit reached.");
    }
}

// Increment user count
incrementUserCount();
incrementUserCount();

// Log user details
console.log(`Current user: ${userName}`);
 



Explanation

  • Constants: MAX_USERS and API_URL are declared using const to indicate that these values should not change. They are named in uppercase with underscores to follow the convention for constants.
  • Variables: userCount and userName are declared using let, and their names are in camel case.
  • Function: The function incrementUserCount uses a descriptive name indicating its purpose. It checks if the userCount is less than MAX_USERS and increments it.
  • This approach ensures that the code is easy to read and understand, making it more maintainable.


Reserved Words in JavaScript

Here are some reserved words that cannot be used as identifiers:

 

  • abstract, arguments, await, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, eval, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, let, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with, yield
  • Using these words as identifiers will result in syntax errors.

 



Practice Excercise Practice now

The Assignment Operator

Basic Assignment

At its core, the assignment operator is used to assign a value to a variable. Here's a simple example:
 


let x;
x = 10; // Assigning the value 10 to the variable x
 

In this case, the value 10 is assigned to the variable x using the = operator.


Variable Initialization

The assignment operator is often used during variable initialization, where a variable is declared and assigned a value in one step:
 

let y = 20; // Declaring variable y and assigning the value 20 in one step


Reassignment

Variables can be reassigned using the assignment operator. This means you can change the value stored in a variable:
 


let z = 30;
z = 40; // Reassigning the value of z from 30 to 40
 


Compound Assignment Operators

JavaScript also provides compound assignment operators, which combine assignment with other operations like addition, subtraction, multiplication, etc. Examples include +=, -=, *=, /=, and %=.

 

let a = 5;
a += 3; // Equivalent to a = a + 3, assigns 8 to a
 


Chaining Assignments

You can chain assignments together to assign multiple variables in a single line:

 

let b, c, d;
b = c = d = 15; // Assigns 15 to b, c, and d simultaneously
 



Destructuring Assignment

JavaScript also supports destructuring assignment, a powerful feature that allows you to extract values from arrays or objects and assign them to variables in a single statement:


Array Destructuring
 

let [first, second] = [1, 2]; // Assigns 1 to first and 2 to second
 


Object Destructuring

 

let { name, age } = { name: 'Alice', age: 30 }; // Assigns 'Alice' to name and 30 to age
 


Default Values

Destructuring assignment can also include default values:

 

let [x = 1, y = 2] = [undefined, 3]; // x will be 1 (default), y will be 3
 


Assignment and Comparison

It's important to note that the assignment operator (=) is distinct from the equality operator (== or ===). The assignment operator assigns a value, while the equality operator checks for equality.

 

 



Practice Excercise Practice now

JavaScript Data Types

JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type. Instead, they can hold values of various types. Here's an explanation of JavaScript data types with examples:


1. Primitive Data Types

These are the basic data types in JavaScript:


a. Number

Represents both integers and floating-point numbers.


Example:


let age = 30; // integer
let temperature = 98.6; // floating-point number
 



b. String

Represents text enclosed in single or double quotes.


Example:


let name = 'John Doe';
let message = "Welcome to JavaScript!";
 


c. Boolean

Represents true or false values.
 

Example:


let isLogged = true;
let isExpired = false;
 



d. Undefined

Represents a variable that has been declared but not assigned a value.


Example:


let x;
console.log(x); // Outputs: undefined
 



e. Null

Represents an intentional absence of any value.

Example:


let score = null;
f. Symbol
 

Introduced in ES6, represents a unique and immutable data type.


Example:


const KEY = Symbol('unique key');
 



2. Complex Data Types

These are also known as reference types and can hold collections of data or complex entities:

a. Object

Represents a collection of key-value pairs where the keys are strings.



Example:


let person = {
    name: 'Alice',
    age: 25,
    isAdmin: false
};
 



b. Array

Represents a list-like object of elements.


Example:

l
et colors = ['red', 'green', 'blue'];
 



c. Function

Represents a reusable block of code.


Example:


function greet(name) {
    console.log(`Hello, ${name}!`);
}
 


3. Data Type Checking

JavaScript provides operators and methods for checking the data type of a variable:


a. typeof Operator

Returns a string indicating the type of a variable.


Example:

console.log(typeof 42); // Outputs: "number"
console.log(typeof 'hello'); // Outputs: "string"
console.log(typeof true); // Outputs: "boolean"



b. instanceof Operator

Checks whether an object is an instance of a specific object type.
 

Example:


let fruits = ['apple', 'banana', 'orange'];
console.log(fruits instanceof Array); // Outputs: true
 



4. Type Coercion

JavaScript performs implicit type coercion, converting values between types during operations:


a. String Concatenation

Numbers are coerced into strings when concatenated with strings.

Example:
 


let num = 42;
let str = 'The answer is ' + num; // Result: "The answer is 42"
 


b. Numeric Operations

Strings containing numeric characters are coerced into numbers during arithmetic operations.


Example:


let total = '10' - 5; // Result: 5 (string "10" coerced into number)
 


5. NaN and Infinity

JavaScript has special values for representing "not a number" (NaN) and infinity:

a. NaN (Not a Number)

Represents an invalid or unrepresentable value resulting from arithmetic operations.


Example:


console.log(0 / 0); // Outputs: NaN
 


b. Infinity

Represents positive infinity.


Example:


console.log(1 / 0); // Outputs: Infinity
 

JavaScript supports various data types, including primitive types like numbers, strings, booleans, and reference types like objects, arrays, and functions.



Practice Excercise Practice now

Declaring (Creating) JavaScript Variables

1. Variable Declaration

To declare a variable in JavaScript, you use the var, let, or const keyword followed by the variable name. Here's how each keyword works:


a. Using var
 

var age = 30;

 

The var keyword was the traditional way to declare variables in JavaScript. It has function scope, meaning it's scoped to the nearest function block.


b. Using let
 

let name = 'John Doe';

 

Introduced in ES6, let allows block scoping. Variables declared with let are limited to the block (or statement) they are defined in.


c. Using const
 

const PI = 3.14;

 

const also came with ES6 and is used to declare constants. Constants cannot be reassigned a new value once initialized.


2. Variable Naming Rules

When naming variables in JavaScript, you should follow these rules:

 

  • Variable names can contain letters, digits, underscores, and dollar signs.
  • Variable names cannot start with a digit.
  • Variable names are case-sensitive (age is different from Age).
  • Reserved words (e.g., if, else, function) cannot be used as variable names.

3. Examples of Variable Declaration

a. Declaring and Initializing Variables
 


var firstName = 'Alice'; // Using var
let lastName = 'Smith';   // Using let
const MAX_VALUE = 100;    // Using const
 



b. Reassigning Variables
 

let count = 5;
count = count + 1; // Reassigning the value of count


c. Constants
 

const DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 10; // This will throw an error as constants cannot be reassigned.



4. Scope of Variables

Variables declared with var have function-level scope, meaning they are visible throughout the function they are declared in (including inside nested blocks). However, they are not accessible outside the function.

 

Variables declared with let and const have block-level scope. They are limited to the block (enclosed by curly braces) they are defined in.


5. Hoisting

JavaScript hoists variable declarations. This means that variable declarations (not initializations) are moved to the top of their scope during compilation.


Example of Hoisting
 

console.log(name); // Outputs: undefined
var name = 'Alice';

 

Even though name is declared later in the code, it's hoisted to the top, so the code above is interpreted as:

 

var name;
console.log(name); // Outputs: undefined
name = 'Alice';


 



Practice Excercise Practice now

One Statement, Many Variables

The phrase "one statement, many variables" typically refers to the ability in programming languages to declare multiple variables in a single line or statement. This is a common feature in many programming languages, including JavaScript. Let's delve into this concept with examples and explanations.


Declaring Multiple Variables in JavaScript

In JavaScript, you can declare multiple variables in a single statement using either var, let, or const keywords. Here's how you can do it:


Using var:

 
var x = 10, y = 'Hello', z = true;


Using let:
 
let a = 20, b = 'World', c = false;


Using const:
 
const PI = 3.14, MAX_VALUE = 1000, DEBUG_MODE = true;


Example Scenario

Let's consider an example scenario where you might want to declare multiple variables in a single statement.

 
var firstName = 'John', lastName = 'Doe', age = 30, isEmployed = true;


In this example:
  • firstName, lastName, age, and isEmployed are all declared and initialized in one line.
  • firstName and lastName are strings storing the person's name.
  • age is a number representing the person's age.
  • isEmployed is a boolean indicating whether the person is employed or not.
  • Benefits of Declaring Multiple Variables in One Statement
  • Conciseness: It makes the code more compact and readable, especially when dealing with related variables.
  • Ease of Maintenance: Updating or modifying multiple variables at once becomes simpler.
  • Efficiency: It reduces the number of lines of code, which can lead to faster development.


Best Practices

While declaring multiple variables in one statement can be convenient, it's essential to follow best practices:

Clear Naming: Use clear and meaningful variable names to enhance code readability.
Group Related Variables: Declare variables together if they are related or serve a similar purpose.

  • Avoid Overloading: Don't overcrowd a single statement with too many variables; maintain readability.
  • Considerations with var, let, and const
  • Use var for variables with function scope.
  • Prefer let for variables with block scope (introduced in ES6).
  • Use const for constants whose values won't change after initialization.

 



Practice Excercise Practice now

Re-Declaring JavaScript Variables

JavaScript is a versatile and widely-used programming language, essential for creating dynamic and interactive web applications. Understanding how variables work, especially the nuances of re-declaring them, is crucial for writing efficient and bug-free code. This guide explores the different ways of declaring variables in JavaScript, focusing on the implications of re-declaring them using var, let, and const.


Variable Declaration in JavaScript

JavaScript provides three main keywords for declaring variables: var, let, and const. Each has distinct characteristics and behaviors:

  • var: The oldest way to declare variables, introduced in ECMAScript 1.
  • let: Introduced in ECMAScript 6 (ES6), it offers block-scoping.
  • const: Also introduced in ES6, it declares variables with constant values.

var Keyword

When using var, you can re-declare a variable within the same scope without error. This behavior is because var is function-scoped or globally-scoped if declared outside a function.

 

var x = 10;
console.log(x); // Output: 10

var x = 20;
console.log(x); // Output: 20
 
 

In the example above, x is re-declared and reassigned. The JavaScript engine allows this because var does not enforce strict scope boundaries like let and const.


Function Scope

Variables declared with var inside a function are scoped to that function.

 

function example() {
    var y = 30;
    console.log(y); // Output: 30

    var y = 40; // Re-declaration
    console.log(y); // Output: 40
}
 


example();

Here, y is re-declared within the function scope without any issues.


Global Scope

If var is used outside any function, it is attached to the global object, which in browsers is window.

 
var globalVar = 50;
console.log(window.globalVar); // Output: 50


let Keyword

The let keyword introduces block-scoping, which means variables are limited to the block, statement, or expression where they are used. Re-declaring a let variable in the same scope leads to a syntax error.

 

let a = 10;
console.log(a); // Output: 10

// let a = 20; // SyntaxError: Identifier 'a' has already been declared
 

In contrast to var, re-declaring a within the same scope using let is not allowed.


Block Scope

Variables declared with let are only accessible within the nearest enclosing block, such as a loop or an if statement.

 
if (true) {
    let b = 30;
    console.log(b); // Output: 30
}
// console.log(b); // ReferenceError: b is not defined

The variable b exists only within the if block, preventing re-declaration errors and reducing the likelihood of bugs.


Example: Loops

The block-scoping feature of let is particularly useful in loops.
 


for (let i = 0; i < 3; i++) {
    let message = `Iteration ${i}`;
    console.log(message);
}
// console.log(i); // ReferenceError: i is not defined
 
 

Here, i and message are confined to the loop block, avoiding potential conflicts with other parts of the code.


const Keyword

The const keyword is used to declare variables whose values are intended to remain constant. Similar to let, const is block-scoped. However, re-declaration and reassignment of const variables are not permitted.

 

const c = 10;
console.log(c); // Output: 10

// c = 20; // TypeError: Assignment to constant variable.
// const c = 30; // SyntaxError: Identifier 'c' has already been declared
 
 

Once a const variable is assigned a value, it cannot be changed. This immutability is beneficial for maintaining data integrity throughout the code.


Block Scope

Like let, const variables are block-scoped.

 

if (true) {
    const d = 40;
    console.log(d); // Output: 40
}
// console.log(d); // ReferenceError: d is not defined
 

The variable d is restricted to the if block.


Constant Objects and Arrays

While the reference to a const variable cannot be changed, the contents of objects and arrays can be modified.

 

const obj = { key: 'value' };
obj.key = 'newValue'; // This is allowed
console.log(obj.key); // Output: 'newValue'

const arr = [1, 2, 3];
arr.push(4); // This is allowed
console.log(arr); // Output: [1, 2, 3, 4]
 

The references to obj and arr remain constant, but their contents can be altered.


Practical Considerations

Choosing Between var, let, and const

  • var: Generally avoided in modern JavaScript due to its function-scoping and potential for creating bugs through accidental re-declarations.
  • let: Preferred for variables that need to be reassigned but are confined to a specific block scope.
  • const: Used for variables that should not be reassigned, ensuring immutability of the reference.

Avoiding Common Pitfalls

Accidental Global Variables: Omitting var, let, or const when declaring a variable results in a global variable, which can lead to hard-to-debug errors.

 

function faulty() {
    accidentalGlobal = 50; // Declares a global variable
}
faulty();
console.log(window.accidentalGlobal); // Output: 50
 

Hoisting: var declarations are hoisted to the top of their scope, but assignments are not.

 

console.log(hoistedVar); // Output: undefined
var hoistedVar = 10;
 
 

With let and const, accessing variables before declaration results in a ReferenceError.

 

// console.log(hoistedLet); // ReferenceError
let hoistedLet = 20;
 



Best Practices
  • Use const by default, opting for let only when reassignment is necessary.
  • Avoid var to prevent issues related to scope and hoisting.
  • Ensure variables are declared in the smallest scope necessary to enhance code readability and maintainability.

 



Practice Excercise Practice now

JavaScript Arithmetic

JavaScript is a versatile and powerful programming language that provides a robust set of arithmetic operations. These operations are fundamental for performing calculations and manipulating numerical data in various applications. This guide will cover the basic arithmetic operations in JavaScript, including addition, subtraction, multiplication, division, modulus, and more. We'll also discuss some advanced concepts like increment/decrement operators and how JavaScript handles floating-point arithmetic.



Basic Arithmetic Operations

JavaScript supports the following basic arithmetic operations:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%)
  • Addition (+)

The addition operator is used to add two numbers.

 

let a = 5;
let b = 10;
let sum = a + b;
console.log(sum); // Output: 15
 

When the addition operator is used with strings, it performs string concatenation.
 

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe



Subtraction (-)

The subtraction operator subtracts one number from another.

 
let a = 20;
let b = 5;
let difference = a - b;
console.log(difference); // Output: 15


Multiplication (*)

The multiplication operator multiplies two numbers.

let a = 4;
let b = 3;
let product = a * b;
console.log(product); // Output: 12


Division (/)

The division operator divides one number by another.
 


let a = 20;
let b = 4;
let quotient = a / b;
console.log(quotient); // Output: 5
 



Modulus (%)

The modulus operator returns the remainder of a division operation.

 
let a = 10;
let b = 3;
let remainder = a % b;
console.log(remainder); // Output: 1


Increment and Decrement Operators

JavaScript provides two useful operators for incrementing and decrementing values:

  1. Increment (++)
  2. Decrement (--)
  3. Increment (++)

The increment operator increases a number by one. It can be used as a prefix or postfix.

 
let a = 5;
a++;
console.log(a); // Output: 6

let b = 5;
console.log(++b); // Output: 6


Decrement (--)

The decrement operator decreases a number by one. It can also be used as a prefix or postfix.

 
let a = 5;
a--;
console.log(a); // Output: 4

let b = 5;
console.log(--b); // Output: 4


Compound Assignment Operators

JavaScript offers compound assignment operators that combine arithmetic operations with assignment:

  1. Addition assignment (+=)
  2. Subtraction assignment (-=)
  3. Multiplication assignment (*=)
  4. Division assignment (/=)
  5. Modulus assignment (%=)
  6. Addition Assignment (+=)
 
let a = 10;
a += 5;
console.log(a); // Output: 15


Subtraction Assignment (-=)
 
let a = 10;
a -= 3;
console.log(a); // Output: 7


Multiplication Assignment (*=)
 
let a = 10;
a *= 2;
console.log(a); // Output: 20


Division Assignment (/=)
 
let a = 10;
a /= 2;
console.log(a); // Output: 5


Modulus Assignment (%=)
 
let a = 10;
a %= 3;
console.log(a); // Output: 1


Advanced Concepts

Exponentiation (**)

JavaScript also supports the exponentiation operator (**) for raising a number to the power of another number.

 

let a = 2;
let b = 3;
let result = a ** b;
console.log(result); // Output: 8
 


Floating-Point Arithmetic

JavaScript handles both integers and floating-point numbers. However, due to the binary representation of floating-point numbers, you might encounter precision issues.

 

let a = 0.1;
let b = 0.2;
let sum = a + b;
console.log(sum); // Output: 0.30000000000000004
 


To handle precision issues, you can use the toFixed method.
 

let sumFixed = sum.toFixed(2);
console.log(sumFixed); // Output: 0.30


Math Object

JavaScript provides the Math object for more advanced mathematical operations.


Math.sqrt
 
let num = 16;
let squareRoot = Math.sqrt(num);
console.log(squareRoot); // Output: 4


Math.pow
 
let base = 2;
let exponent = 3;
let power = Math.pow(base, exponent);
console.log(power); // Output: 8


Math.round, Math.ceil, and Math.floor
 
let num = 5.7;
console.log(Math.round(num)); // Output: 6
console.log(Math.ceil(num));  // Output: 6
console.log(Math.floor(num)); // Output: 5


Random Numbers

The Math.random method generates a random number between 0 and 1.
 

let randomNum = Math.random();
console.log(randomNum); // Output: a random number between 0 and 1
 

To generate a random number within a specific range:

 

let min = 1;
let max = 10;
let randomNumInRange = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomNumInRange); // Output: a random number between 1 and 10
 


Practical Examples
  • Calculating the Area of a Circle
  • To calculate the area of a circle given its radius:
 
let radius = 5;
let area = Math.PI * radius ** 2;
console.log(area); // Output: 78.53981633974483


Converting Fahrenheit to Celsius

To convert a temperature from Fahrenheit to Celsius:

let fahrenheit = 100;
let celsius = (fahrenheit - 32) * (5 / 9);
console.log(celsius); // Output: 37.77777777777778


Simple Interest Calculation

To calculate simple interest:

let principal = 1000;
let rate = 5;
let time = 2;
let interest = (principal * rate * time) / 100;
console.log(interest); // Output: 100
 

JavaScript provides a comprehensive set of arithmetic operations, from basic addition and subtraction to more complex calculations involving exponentiation and the Math object. Understanding these operations and how to apply them is crucial for performing calculations and developing dynamic applications.


 



Practice Excercise Practice now

JavaScript Underscore (_)

Underscore.js is a JavaScript library that provides a comprehensive set of utility functions for common programming tasks. It offers support for functional programming principles, making it easier to work with arrays, objects, and other data types. This guide will provide an overview of Underscore.js, its key features, and some practical examples of its use.


Introduction to Underscore.js

Underscore.js is a utility-belt library for JavaScript that provides numerous helper functions for tasks such as data manipulation, functional programming, templating, and more. It allows developers to write cleaner and more concise code by abstracting common operations into simple function calls.

To use Underscore.js, you need to include it in your project. You can either download the library from the official website or include it via a CDN. Here’s how you can include it using a CDN:

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script>

Once included, all Underscore functions are available through the _ object.


Key Features and Examples
Collections

Underscore.js provides various functions for dealing with collections (arrays and objects).


_.each

The _.each function iterates over a list of elements, yielding each in turn to an iteratee function.

 
let numbers = [1, 2, 3, 4, 5];
_.each(numbers, function(num) {
  console.log(num);
});
// Output: 1, 2, 3, 4, 5


_.map

The _.map function produces a new array of values by mapping each value in a list through a transformation function (iteratee).

 
let numbers = [1, 2, 3, 4, 5];
let squares = _.map(numbers, function(num) {
  return num * num;
});
console.log(squares);
// Output: [1, 4, 9, 16, 25]


_.filter

The _.filter function looks through each value in a list and returns an array of all the values that pass a truth test (predicate).

 
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = _.filter(numbers, function(num) {
  return num % 2 === 0;
});
console.log(evenNumbers);
// Output: [2, 4]


Arrays

Underscore.js provides several functions for manipulating arrays.


_.first and _.last

The _.first function returns the first element of an array. If a number is provided, it returns the first n elements.

 

let numbers = [1, 2, 3, 4, 5];
console.log(_.first(numbers));
// Output: 1
console.log(_.first(numbers, 3));
// Output: [1, 2, 3]
 
 

The _.last function works similarly but returns the last element(s).

let numbers = [1, 2, 3, 4, 5];
console.log(_.last(numbers));
// Output: 5
console.log(_.last(numbers, 3));
// Output: [3, 4, 5]


_.uniq

The _.uniq function returns a duplicate-free version of an array.

 
let numbers = [1, 2, 1, 4, 1, 3];
let uniqueNumbers = _.uniq(numbers);
console.log(uniqueNumbers);
// Output: [1, 2, 4, 3]


_.flatten

The _.flatten function flattens a nested array (the nesting can be to any depth).

 

let nestedArray = [1, [2], [3, [[4]]]];
let flatArray = _.flatten(nestedArray);
console.log(flatArray);
// Output: [1, 2, 3, 4]
 


Objects

Underscore.js offers functions for manipulating objects.


_.keys and _.values

The _.keys function retrieves all the names of the object's properties.

 
let obj = { one: 1, two: 2, three: 3 };
let keys = _.keys(obj);


console.log(keys);
 
// Output: ['one', 'two', 'three']

The _.values function retrieves all the values of the object's properties.

 

let obj = { one: 1, two: 2, three: 3 };
let values = _.values(obj);
console.log(values);
// Output: [1, 2, 3]
 


_.extend

The _.extend function copies all properties from source objects to a destination object.

 
let obj1 = { a: 1 };
let obj2 = { b: 2 };
let extendedObj = _.extend(obj1, obj2);
console.log(extendedObj);
// Output: { a: 1, b: 2 }


Utility Functions

Underscore.js also includes a variety of utility functions.


_.noConflict

The _.noConflict function returns the _ variable to its previous owner and returns a reference to the Underscore object.

 
let underscore = _.noConflict();
// Now `underscore` can be used in place of `_`


_.identity

The _.identity function returns the same value that is used as the argument. This function is often used as a default iteratee.

let numbers = [1, 2, 3, 4, 5];
let identities = _.map(numbers, _.identity);
console.log(identities);
// Output: [1, 2, 3, 4, 5]


_.times

The _.times function invokes a given function a specified number of times.

 
_.times(3, function(n) {
  console.log(n);
});
// Output: 0, 1, 2


Practical Examples
Example 1: Grouping Objects by Property

Suppose you have an array of objects representing people and you want to group them by age.

 

let people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 }
];

let groupedByAge = _.groupBy(people, 'age');
console.log(groupedByAge);
// Output:
// {
//   25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
//   30: [{ name: 'Bob', age: 30 }]
// }
 

Example 2: Finding the Maximum Value in an Array

Using Underscore.js, you can find the maximum value in an array with the _.max function.

let numbers = [10, 5, 100, 2, 1000];
let maxNumber = _.max(numbers);
console.log(maxNumber);
// Output: 1000
 

Example 3: Deep Cloning an Object

To deep clone an object, you can use a combination of _.clone and _.extend.

 

let obj = { a: 1, b: { c: 2 } };
let deepClone = _.clone(obj);
deepClone.b.c = 3;
console.log(obj.b.c); // Output: 2 (original object remains unchanged)
console.log(deepClone.b.c); // Output: 3
 

 



Practice Excercise Practice now

Previous Next
COMPANY
  • About us
  • Careers
  • Contact Us
  • In Press
  • People
  • Companies List
Products
  • Features
  • Coding Assessments
  • Psychometric Assessment
  • Aptitude Assessments
  • Tech/Functional Assessments
  • Video Assessment
  • Fluency Assessment
  • Campus
 
  • Learning
  • Campus Recruitment
  • Lateral Recruitment
  • Enterprise
  • Education
  • K 12
  • Government
OTHERS
  • Blog
  • Terms of Services
  • Privacy Policy
  • Refund Policy
  • Mart Category
Partner
  • Partner Login
  • Partner Signup

Copyright © RVR Innovations LLP 2025 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP