Top Stories

Ankaj Gupta
August 19, 2020

Access properties in javascript

JavaScript Fundamentals

How to Access JavaScript Object Properties (Dot vs Bracket)

JavaScript offers two primary syntaxes for reading and writing object properties: dot notation and bracket notation. Mastering both patterns ensures your code works with dynamic keys, external data, and reserved words.

Dot Notation

Concise, autocomplete friendly, works with valid identifiers (letters, digits, underscores).

Bracket Notation

Handles dynamic property names, strings with spaces, numbers, and characters disallowed in identifiers.

Dot Notation

const book = {
    id: 2,
    title: "JavaScript Essentials",
    author: "Coder Website"
};

console.log(book.id);    // 2
console.log(book.title); // "JavaScript Essentials"

Remember: Property names must be valid identifiers (no spaces or hyphens) to use dot notation.

Bracket Notation

Bracket notation accepts any string or expression inside the brackets. Use it for keys with spaces, numbers, or when using variables.

const dynamicKey = "title";

console.log(book[dynamicKey]); // "JavaScript Essentials"
console.log(book["author"]);   // "Coder Website"

When You Must Use Bracket Notation

Keys with Spaces or Hyphens

const movie = {
    "release date": "2024-08-01"
};

console.log(movie["release date"]); // works
console.log(movie.release date);     // SyntaxError

Numeric Property Names

const stats = {
    1: "Bronze",
    2: "Silver",
    3: "Gold"
};

console.log(stats[1]); // "Bronze"
console.log(stats.1);  // SyntaxError

Working with Dynamic Keys

External data (e.g., API responses) often requires dynamic property access.

const response = {
    metrics: {
        visits_2024: 12000,
        visits_2023: 9800
    }
};

function getMetric(year) {
    const key = `visits_${year}`;
    return response.metrics[key] ?? 0;
}

console.log(getMetric(2024)); // 12000

Dot vs Bracket at a Glance

Scenario Preferred Syntax Reason
Static, known keys Dot notation Cleaner syntax, IDE autocomplete support
Keys with spaces or symbols Bracket notation Dot notation is invalid syntax
Access via variables Bracket notation Allows expression evaluation inside brackets
Numeric keys Bracket notation Dot notation treats numbers as invalid identifiers

Key Takeaways

  • Use dot notation when property names are static and valid identifiers.
  • Switch to bracket notation for dynamic keys, user-generated data, or properties with special characters.
  • Combine both approaches for readable, resilient code that adapts to different data shapes.
JavaScript
Read
Ankaj Gupta
August 18, 2020

JavaScript check property exists

JavaScript Reference

Check if a JavaScript Object Has a Property

Objects in JavaScript are flexible—you can add or remove properties at runtime. To write defensive code, confirm a property exists before using it. This guide compares the in operator and hasOwnProperty() method.

What You’ll Learn

  • How the in operator works
  • When to prefer hasOwnProperty()
  • Pros and cons of each approach

Reminder: Prototype chains mean an object may inherit properties you didn’t add explicitly. These checks help avoid unexpected behavior.

Using the in Operator

The expression 'property' in object returns true if the property exists either directly on the object or somewhere along its prototype chain.

const book = { title: "JavaScript" };

console.log('title' in book); // true
console.log('id' in book);    // false
console.log('toString' in book); // true (comes from Object.prototype)

Using hasOwnProperty()

The hasOwnProperty() method checks only the object’s own properties, ignoring inherited ones.

console.log(book.hasOwnProperty('title'));    // true
console.log(book.hasOwnProperty('id'));       // false
console.log(book.hasOwnProperty('toString')); // false (inherited)

Comparing in vs hasOwnProperty()

Scenario Use Reason
Need to check prototype chain too 'property' in object Covers inherited properties
Verify only custom/own keys object.hasOwnProperty('property') Ignores prototype pollution

Putting It Together

const article = Object.create({ slug: 'shared-slug' });
article.title = 'Understanding Property Checks';

console.log('title' in article);          // true
console.log(article.hasOwnProperty('title')); // true

console.log('slug' in article);              // true (inherited)
console.log(article.hasOwnProperty('slug')); // false

Recommendation: Use hasOwnProperty() to guard user-controlled data, and fall back to in when prototype values should count.

Reusable Utility Helper

export function hasOwn(object, key) {
    return Object.prototype.hasOwnProperty.call(object, key);
}

// Example usage
const config = { theme: 'dark' };
console.log(hasOwn(config, 'theme'));   // true
console.log(hasOwn(config, 'layout')); // false

Key Takeaways

  • The in operator returns true for own and inherited properties.
  • hasOwnProperty() checks only own properties, guarding against prototype pollution.
  • Wrap property checks in utility helpers to centralize edge-case handling across your codebase.
JavaScript
Read
Ankaj Gupta
August 07, 2020

How to change const variable value in javascript

JavaScript const variable value change

As you known, Variable declare with const keyword you can not change later in program, but this condition is apply only for constant primitive values not for constant object or array.

Note : If you declare constant object or array value with const keyword, You can change or add the properties of const variables.

Let's see the examples:

 ➤ Example 1 : constant primitive values;

  • If we assign a primitive value to a constant, we can't change the primitive value.

  1. <script>
  2. const x = 25;//output : 25

  3. x++; //ERROR, not allowed

  4. x = 20; //ERROR, not allowed

  5. x = x+5; //ERROR, not allowed

  6. </script>

# Let see how to change the value of const variable

 ➤ Example 2: constant objects values;

  • You can change the properties of a constant object.

  1. <script>
  2. //You can create a const object.

  3. const student = {name:"Ankaj", branch:"CS"};

  4.  

  5. //You can change a property.

  6. student.name = "Ankaj Gupta"; //Allow

  7.  

  8. //You can add a property.

  9. student.rollno = "45"; //Allow

  10.  

  11. //Note : But you can't re-assign a constant object.

  12. student = {name:"Anmol", branch:"initialize"}; //ERROR, not allowed

  13. </script>

 ➤ Example 3 : constant array values;

  • You can change the elements of a constant array.

  1. <script>
  2. //You can create a const array.

  3. const student = ["Name", "Branch", "Rollno"];

  4.  

  5. //You can change an element.

  6. student[2] = "Enroll_No"; //Allow

  7.  

  8. //You can add an element.

  9. student.push("Gender"); //Allow

  10.  

  11. //Note : But you can't reassign a constant array.

  12. student = ["Name", "Branch", "Enroll_No", "Gender"];//ERROR, not allowed

  13. </script>
JavaScript
Read
Ankaj Gupta
July 19, 2020

Limitations of JavaScript

Disadvantage of JavaScript

There are lot of disadvantage of JavaScript in Web Technologies some disadvantage of JavaScript are following :

1. Security :
  • As you know that JavaScript code is viewable to the user, others may use it for malicious purposes. These practices may include using the source code without authentication and also, it is very easy to place(append) some code into the site that compromises the security of data over the website.

  • The JavaScript code executes on the user's computer(client-side) in some cases it can be exploited for malicious purposes. The malicious code can still be executed complying with the restrictions set, this is one reason some people choose to disable JavaScript.

2. JavaScript can be disabled :
  • All browser's provides option to disable JavaSript to run by the user due to specific security reasons. If your website is highly dependent on JavaScript codes it is sometimes difficult to support to run your web application.

3. Browser support:
  • The browser interprets JavaScript differently in different browsers, So the code must be run on various platforms before publishing.

  • The older browsers don’t support some new functions and we need to check them as well as you test your script in all the major browsers you should be safe. Also, there are services out there that will allow you to test your javascript code automatically on check in of an update to make sure all browsers support your javascript code

4. Rendering Stopped :
  • In JavaScript a single code error can stop the rendering of the entire JavaScript code on the website. However, the browsers are extremely tolerant of these type errors.

5. Single Inheritance :
  • JavaScript not supports multiple inheritance it only supports single inheritance and . Some programs may require object-oriented language characteristic.

6. File Download :
  • As you know that JavaScript code is viewable to the user, JavaScript file is download on client machine so anyone can read the code and reuse it.

Why people disabled JavaScript code ?

JavaScript code may be exploited for the malicious purposes if it executes on the users computer, that's way many people(user's) choose to disable JavaScript, because they know about its security flaws. Therefore, developers need to be careful while coding so that the script they write is not too easily interrupted.

JavaScript
Read
Ankaj Gupta
July 15, 2020

Escape sequences in JavaScript | JavaScript escape character

JavaScript escape sequences

Escape sequences in a JavaScript string are used to express code units based on code point numbers and It is a mechanism for quoting a single character, Such as : quotes, backslash and control characters.

The backslash('\') is the escape character, JavaScript was built at a time when unicode was a 16-bit character set, so all character, make a string with just one character in it.

JavaScript has 3-escape types, one which was introduced in ECMAScript 2015 :

  1. Unicode escape sequence.

  2. Hexadecimal escape sequence.

  3. Codepoint escape sequence.

# Type Range Digits Format Example
1 Hexadecimal escape 0x00 to 0xFF 2 \xDD \x1E
2 Unicode escape \251 4 \uDDDD \u006E
3 Codepoint escape 0x00 to 0x10FFFF 1 to 6 \u{D..D} \u{1F639}

Let’s see them escape sequences in more detail :

1.) Unicode escape sequence :

  • The unicode escape sequence is \u<hex>, where \u is a prefix followed by a hexadecimal number <hex> with a fixed length of 4 digits.

  • If you want to escape code points from the entire BMP, then you can use an unicode escape sequence.

  • For example '\u000B1' (Plus OR Minus symbol '±') or '\u0222B' (Integral symbol '∫')

Let’s see the use of unicode escape sequences:

Example :

  1. <script>
  2. const str = 'I\u0020learn \u0055nicode';

  3. console.log(str); //=>'I learn Unicode'

  4. const reg = /\u0055ni.*/;

  5. console.log(reg.test('Unicode')); //=>true

  6. </script>
Important point of unicode escape sequence :
  • An unicode escape sequence can escape code points in a limited range: from U+0000 to U+FFFF (all BMP code points) because only 4 digits are allowed.

  • The unicode escape sequence most of the time this is enough to represent the commonly used symbols.

2.) Hexadecimal escape sequence :

  • The shortest form is named hexadecimal escape sequence: \x<hex>, where \x is a prefix followed by a hexadecimal number <hex> with a fixed length of 2 digits.

  • For example : '\x40' (symbol '@') or '\x3F' (symbol '?').
Let’s see the use of hexadecimal escape sequences :

Example :

  • The hexadecimal escape sequence in a string literal or regular expression looks this way.

  1. <script>
  2. const str = 'I le\x61rn \x48\x65xadecimal';

  3. console.log(str); //=>'I learn Hexadecimal'

  4. const reg = /\x4A\x61va.*/;

  5. console.log(reg.test('JavaScript')); //=>true

  6. </script>
Important point of hexadecimal escape sequence :
  • A hexadecimal escape sequence can escape code points in a limited range: from U+00 to U+FF because only 2 digits are allowed.

  • But hexadecimal escape is nice for use, Because it’s short.

3.) Codepoint escape sequence :

  • ECMAScript 2015 provides escape sequences that represent code points from the entire Unicode space: U+0000 to U+10FFFF, i.e. BMP and astral planes.

  • The new format is called code point escape sequence: \u{<hex>}, where <hex> is a hexadecimal number with a variable length of 1 to 6 digits.

  • For example : '\u{4B}' (symbol 'K') or '\u{1F620}' (Angry face symbol 😡).

Let’s see the use of Codepoint escape sequence :

Example :

  1. <script>
  2. const str = 'Angry face \u{1F620}';

  3. console.log(str); //=>'Angry face 😡'

  4. const reg = /\u{1F620}/u;

  5. console.log(reg.test('Angry face 😡')); //=>true

  6. </script>
Important point of Codepoint escape sequence :
  • Notice that the regular expression /\u{1F620}/u has a special flag u.

The following characters are reserved in JavaScript strings :

# Escape sequences Result Description
1 \' ' Single quotation
2 \" " Double quotation
3 \\ \ Backslash
Seven other escape sequences are valid in JavaScript :
# Escape sequences Description Unicode
1 \b Backspace U+0008
2 \f Form feed U+000C
3 \n New line U+000A
4 \r Carriage Return U+000D
5 \t Horizontal Tabulator U+0009
6 \v Vertical Tabulator U+000B
7 \0 null character U+0000

Note : Important points of escape sequence;

  • '\0' : null character (U+0000 NULL) (only if the next character is not a decimal digit; else it is an octal escape sequence)

  • Escape sequences strings must be written within quotes,Otherwise JavaScript will misunderstand this string:

JavaScript
Read
Ankaj Gupta
March 22, 2019

Boolean datatype in javascript

JavaScript Boolean Datatype

Boolean data-type represents a logical truth value, either true or false, that are associated with the logic branch of mathematics. You can assume the values as "on or off", "yes or no", or "correct or incorrect" or "1 or 0".

It is used to represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.

Note : Boolean values are very commonly are used when testing conditions, like condition and looping statements.

let's see an example of Boolean datatype :

 ➤ Example :

<script>
    var a =10, b =25, c = 15;
    document.write(b > a);  // Output: true
    document.write(b < c);  // Output: false
</script>
JavaScript
Read
Ankaj Gupta
March 17, 2019

What are the Different Data Types in JavaScript

Basically data types are used to classify one particular type of value(data), that can be represented and manipulated data in a programming language.

Introduction of datatype

A datatypes is the specific category of information that a variable contain. It classify types of data such as string, boolean or numbers etc. So that, It determines the possible values for that particular type.

The data-type type also governs the kinds of operations that can be performed on a variable. This is important because the specific data-type you use will determine what values you can assign to it and what you can do to it.

Note : Datatypes in javascript means the type of data stored in variable.

Why data-type is used in programming language ?

The conscept of data-types is often difficult for beginning programmers to grasp because in real life you don't often distinguish among different types of information. If someone asks you for your name, your age or the current time, you dont't usually stop to consider that your name is a text string and that your age and current times are numbers.

  • However, a variables specific data-type is very important in programming because the data-type helps determine how much memory the computer allocates for the data stored in the variable.

  • JavaScript classifies data-type into 3-section :

    1.) Primitive Datatype : Following are the primitive data-type that JavaScript supports.

    • Numbers(Numerical Data).

    • String(Text Data).

    • Boolean.

    • Symbol.

    2.) Special Datatype : Following are the Special data-type that JavaScript supports.

    • Undefined

    • Null

    3.) Non-Primitive Datatype : Following are the non-primitive data-type that JavaScript supports.

    • Array

    • Function, Object and Properties.


1.) Primitive Datatypes :

  • Datatype's that can be assigned only a single value with no additional properties and methods are called primitive types.

  • Primitive defines immutable values and was introduced recently by ECMAScript standard, It can be stored in the fixed amount of memory available.

Let's see an example of primitive data-type :

 ➤ Example : Copying a primitive.

    In this example, The original was not changed, we can only change the copy.

<script>
    var a = 20;  // assign `20` to `a`
    var b = a;   //copy the value of `a` to `b`
    b = 25;      //assign `25` to `b`
    console.log(a)  // =>20
</script>

Note : Primitive types are also known as simple types or scalar types.

JavaScript supports 4-types of primitive data types described in table :

 Datatype Description Example value
Number Represents numeric(Positive or negative numbers with or without decimal places, or number written using exponential notation) values. 9, 9.5 etc.
String A string (or a text string) is a series of characters. "Hello" “Hello Coder” etc.
Boolean A logical value of true or false. true, false.
Symbol (ECMAScript 6)

2.) Special Datatype :

  • Special data-type are also known as Primitive types.

  • Javascript has 2-more literals, null and undefined, that is considered to be objects.

Following are the Special data-type that JavaScript supports, described in table:

 Datatype Description Example value
Undefined represents undefined value(A variable that has never had a value assigned to it, has not been declared, or does not exits). Undefined value
Null represents numeric values(An empty value). Null value

3.) Non-Primitive Datatypes :

  • Datatype's that Objects can contain multiple values are called non-primitive types. It is same as object in the class. We can define attributes and methods to composite data-types.

  • A Non-Primitive datatypes can contain other values. Since the contents of a reference type can't fit in the fixed amount of memory available for a variable, the in memory value of a reference type is the reference itself (a memory address).

  • For instance :

    • Array

    • RegExp

    • Function, Object and Properties.

Let's see an example of non-primitive data-type :

 ➤ Example : Copying a reference;

    The original was also changed, since the reference got copied.

<script>
    var data = {number: 22 };  //assign the reference of a new object to `data`.
    var b = data;   //copy the reference of the object inside `data` to new variable `b`.
    b.number = 75;  //modify the contents of the object `b` refers to.
    console.log(data);  //=> { number : 37 }
</script>

Note : Non-Primitive type are also known as : Reference types or Composite data-type or Complex types or container types.

JavaScript contain following non-primitive data types, described in table:

 Datatype Description
Array represents group of similar values.
RegExp represents regular expression.
Object represents instance through which we can access members.
JavaScript
Read
Ankaj Gupta
March 16, 2019

Define dynamic typing in JavaScript

Javascript Dynamic Typing

JavaScript is a dynamically data typed language, this means that type checking is done at runtime rather than compile time.

Dynamic Typing means that, define a data-type of a variable does't need to be specified, any variable can be used to hold any/different data types. They can easily change from one data type to another data type.

  • For instance : Ruby, Python, JavaScript etc.

Let's see an example of Dynamic Typing in JavaScript :

 ➤ Example :

    In this example, the variable myName change from string to number and then boolean.

<script>
  let myName = 'Ankaj Gupta';  //Ankaj Gupta
  myName = 100;  //100 
  myName = true;  //true
</script>
Example explained :
  • In this example, the variable myName, defined as a variable by the let keyword, can be assigned to hold different data types, or can be initialized.

  • Each of the variables myName above can be set to any data type available in JavaScript. They do not need to be explicitly declared with a data type before they are used.

JavaScript
Read
Ankaj Gupta
March 01, 2019

var vs let vs const

JavaScript has 3-different keywords to declare a variable.

Example : var, let, and const

Let’s see the difference between var vs let vs const:

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No
JavaScript
Read
Ankaj Gupta
February 22, 2019

var vs let in Javascript | Difference between let and var

Difference between let and var in Javascript

There has been a lot of confusion about the use of var and let in Javascript. So here we will see difference between var and let , so that you can easily decide what to use where and when.

Let’s see the difference between var and let

# var let
1 var keyword was introduced with JavaScript. let keyword was introduced in ES 2015(ES6).
2 var statement is used to Create a function variable. let is similar to var scope, and it allows you to create a block-scoped variable.
3 Using var keyword to define variable globally (Global scope). let variables work the same as var when used in a Global scope.
4 var variables can be accessed in the window object. while let variables can't be accessed in the window object because they cannot be globally accessed.
5 Using var keyword to define variable locally (Function scope). let variables work the same as var when used in a function scope.
6 var keyword is not block scoped. let keyword is block scoped.
7 Variables declared with var is hoisted to the top. Variables declared with let is not hoisted to the top.
8 var variables can be redeclared in the same scope. let variables can't be re-declared in the same scope.

Let’s see the var vs let in details with examples :

1.) Global scope :

  • var and let variables work the same way when used in a global scope.

  ➤ Example 1: Global scope;

<script>
    var varVariable = “I am global variable.”;
    let letVariable = “I am also global variable.”;
</script>

2.) Global window object :

  • Global variables defined with let variable will not be added to the global window object like those defined with var.

  ➤ Example 2: Global window object;

  • Thus let variables can't be accessed in the window object because they cannot be globally accessed.

  1. <script>

  2. var varVariable = “I am var variable.”;

  3. let letVariable = “I am let variable.”;

  4. //Say, here we have two variables declared. let us see what output it actually gives you.

  5. console.log(window.varVariable); //=> I am var variable.

  6. console.log(window.letVariable); //=> undefined

  7. </script>

3.) Function scope :

  • var and let variables work the same way when used in a function scope.

  ➤ Example 3: Function scope;

<script>
    function display(){
       var varVariable = "I am var variable.";
       let letVariable = "I am let variable.";
    
       console.log(varVariable); //I am var variable.
       console.log(letVariable); //I am let variable.
    }  
    display();     
</script>

4.) Block scope :

  • Variable defined with var keyword is not block scoped.

  ➤ Example 4.1: For loop using var variable;

<script>
    for(var i=0; i<=5; i++){
       console.log(i); //i is visible here  
    }  
    console.log(i); //i is visible here    
</script>
  • Variable defined with let keyword is block scoped.

  ➤ Example 4.2: For loop using let variable;

<script>
    for(let i=0; i<=5; i++){
       console.log(i); //i is visible here  
    }  
    console.log(i); //Error     
</script>

5.) Variable hoisting :

  • Variables declared with var are hoisted to the top.

  ➤ Example 5.1: Variable hoisting with var;

<script>
    console.log(name); //undefined
    var name = "I am var variable";
</script>
  • Variables declared with let are not hoisted to the top.

  ➤ Example 5.2: Variable hoisting with let;

<script>
    console.log(name); //ReferenceError
    let name = "I am let variable";
</script>

6.) Re-declaration :

  • let variables cannot be re-declared while var variable can be re-declared in the same scope.

  ➤ Example 6.1: var variable re-declaration in same scope;

Variables defined with var keyword can be redeclared in the same scope.

<script>
    var a = 10; 
    var a = 20; //20
</script>

  ➤ Example 6.2: let variable re-declaration in same scope;

Variables defined with let keyword can't be redeclared in the same scope.

<script>
    let a = 10; 
    let a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>
JavaScript
Read
Ankaj Gupta
February 22, 2019

How to use 'const' keyword in JavaScript?

const is one of 3-keywords you can use to declare variables. There are 2-other keywords – let and var. All 3-keywords declare variables, but they’re slightly different from each other.

Const in JavaScript

The const keyword was introduced in ES6 to allow create a block scope variables, same as let. In JavaScript, const does not mean constant, it means one-time assignment.

It allow to create an immutable and mutable variables. Immutable variables means, variables whose values cannot be modified(change) in programming are known as immutable, while values that can be changed are known as mutable.

# Declaring JavaScript Const Variables:

Syntax :

Let’s see the syntax of const keyword :

 ➤ Syntax :

<script>
    const variable_name = value;
</script>
Parameter :
  • const : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : Required, Initializing constant value.

Note : A variable declared with const must be initialized.

# immutable and mutable variable in const

It does't define a constant value. It defines a constant reference to a value. Because of this, we can't change constant primitive values, but we can change the properties of constant objects or array.

Let's see an example of immutable variable in const :

 ➤ Example 1 : Immutable variable;

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

Let's see an example of mutable variable in const :

 ➤ Example 2 : Mutable variable;

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow
</script>

# Scope of const keyword :

1.) Global scope :

  • Using const keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    const x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        if(true)
         {
          console.log("Inside block :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using const keyword to define variable locally (local scope). It can't be accessed outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       const a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  const age = 22;
  if (age > 21)
    {
      const message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Variable defined with ‘const’ keyword are not hoisted to the top. So if you try to accessed the variable before declaration it, javascript throw a Reference Error.

Note : Because you can not re-assign a const, you know it is not possible to hoist them.

Let's try to create an exaple :

 ➤ Example : Variable hoisting with const;

    Variables declared with const are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    const name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of const keyword in JavaScript :

  • Assigned when Declared : The const variable must be both declared and initialised. If you don't assign variables value at declaration time, It will give the SyntaxError.

 ➤ Syntax :

<script>
    const constant_name = value;
</script>

 ➤ Example Incorrect : Variable declared without initialization;

    You need to initialize it with a value when declaring otherwise will have the SyntaxError.

<script>
    const name;  //SyntaxError: Missing initializer in const declaration
</script>

 ➤ Example correct : Variable declared with initialization;

<script>
    const name= "Ankaj";
</script>
  • Block-scope : Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the const keyword have Block Scope.

<script>
    if(true)
    {
      const a=10;
      document.write(a); //Outpt : 10
    }
    document.write(a); //ReferenceError: a is not defined
</script>
  • Variable Re-declaration : Unlike var, Constant variable can't declare the same variable more than one time using ‘const’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Re-declaring a variable with const, in same scope is allowed.

<script>
    const a = 10; 
    const a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in another scope;

    Re-declaring a variable with const, in another scope not allowed.

<script>
    const a = 10; //Global scope
    function display()
    {
      const a= 20; //Local scope
    }
    if(true)
    {
      const a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variables declared with var or let can be changed later in the program. Once a const variable is initialized, its value can never be changed again, and it can’t be reassigned to a different value.

 ➤ Example : Re-assigned a new value;

    The code will throw an error when we try to re-assign the existing const variable.

<script>
    // Assign value to x variable
    const x=10;
    //Reassign variable with a new value
    x = 20; //TypeError: Assignment to constant variable.
</script>
  • Dynamic type : As you known, const variables can not be re-assign, that's why variables declared with const keyword are not dynamic type.

 ➤ Example : Dynamic type variables;

<script>
    consr myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //Error
    myName= true; //Error
</script>

# How to change const values in javascript ?

  • As you known, Variable declare with const keyword you can not change later in program, but this condition is apply only for constant primitive values not for constant object or array.

  • If you declare constant object or array value with const keyword, You can change or add the properties of const variables.

Let's see the examples :

 ➤ Example i : constant primitive values;

    If we assign a primitive value to a constant, we can't change the primitive value.

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

 ➤ Example ii : constant objects values;

    You can change the properties of a constant object.

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow

    //Note : But you can't re-assign a constant object.
    student = {name:"Anmol", branch:"ECE"};  //ERROR, not allowed
</script>

 ➤ Example iii : constant array values;

    You can change the elements of a constant array.

<script>
    //You can create a constant array.
    const student = ["Name", "Branch", "Rollno"];

    //You can change an element.
    student[2] = "Enroll_No"; //Allow

    //You can add an element.
    student.push("Gender"); //Allow

    //Note : But you can't reassign a constant array.
    student = ["Name", "Branch", "Enroll_No", "Gender"];  //ERROR, not allowed
</script>
JavaScript
Read
Ankaj Gupta
February 16, 2019

let keyword in javascript

let keyword is introduced in 2015(ES6). It is similar to var scope, and it allows the variable’s value to be changed during the course of the program execution.

Let in JavaScript

The let statement allows you to create/declared a block-scoped variable. Block-scoped means whenever a variable is created with let, it will only exist within its block(pair of curly braces).

It is similar to the variable we declare in other languages like : .NET, Java, etc.

# Declaring JavaScript let Variables:

Syntax :

Let’s see the syntax of let keyword :

 ➤ Syntax :

<script>
    let variable_name = value;
</script>
Parameter :
  • let : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : ptional, Initial value assign at the time of declaration.


Let’s see an example of let keyword in JavaScript :

 ➤ Example :

<script>
    function display() {
       let a =10;
       console.log(a);   //Output : 10
       if(true) {
          let a=20;
          console.log(a); //Output : 20
        }
        console.log(a);  //Output : 10
     }  
    display();     
</script>

# Scope of let keyword :

1.) Global scope :

  • Using let keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    let x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++) {
          console.log("Looping time :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using let keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       let a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  let age = 22;
  if (age > 21)
    {
      let message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Unlike var keyword, The variable declared using ‘let’ keyword is not hoisted. So if you try to use the variable before declaring it, javascript throw a Reference Error.

Let's try to create an exaple :

 ➤ Example :Variable hoisting with let;

    Variables declared with let are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    let name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me



Important point's of let keyword in JavaScript :

  • Variable access befor declaration : let variables are registered at the top of the block, But when the variable is accessed before declaration, JavaScript throws a ReferenceError.

 ➤ Example:

    let can't use variable before the declaration otherwise gives an error.

<script>
    document.write(x); //ReferenceError: x is not defined
</script>
  • Variable use without initialization : The let statement creates and initializes variables inside the block scope. If you don't assign variables value at declaration time, By default JavaScript automatically a declared assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    let name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the let keyword have Block Scope.

<script>
    for(let i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //ReferenceError: i is not defined
</script>
  • Variable Re-declaration : Unlike var, You can't declare the same variable more than one time using ‘let’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Variables defined with let keywords can't be redeclared in the same scope.

<script>
    let a = 10; 
    let a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in separate scope;

    Variables defined with let keywords can be redeclared in the separate scope.

<script>
    let a = 10; //Global scope
    function display()
    {
      let a= 20; //Local scope
    }
    if(true)
    {
      let a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    let x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with let keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    let myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>
JavaScript
Read
Ankaj Gupta
February 14, 2019

Var in JavaScript

var keyword in JavaScript

The var statement is used to declare(Create) a variable. Until ES2015, var was the only only way to declare variable. Now there are two more options to declare variable: let and const.

Variables declared with var keyword have functional scope variable, This means whenever a variable is created with var in a function, it will only exist within the function.

# Declare variable

Let’s see the syntax of var keyword :

 ➤ Syntax :

<script>
    var variable_name = value;
</script>
Parameter :
  • var: JavaScript reserved keyword.

  • var_name : Name of variable.

  • value : Optional, Initial value assign at the time of declaration.

Note : let and const are block scoped variables. Block scope does not apply to var.

Let’s see the example of var keyword in JavaScript :

 ➤ Example :

    In this example, apple, mango, and totalFruits are variables.

<script>
    var apple = 8;
    var mango = 9;
          
    var totalFruits = apple + mango;
    document.write(totalFruits);
</script>
Output :

17



Scope of var keyword ?

1.) Global scope :

  • Using var keyword to define variable globally. Once you define globally, you can access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script>
    var x=1; //'x' is gloabal variable
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++ )
         {
          console.log("Looping time :",x); // x visible on here
         }
         console.log("Inside function :",x); // x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); // x visible
</script>

2.) Local scope :

  • Using var keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration, Function parameters are always local to that function

 ➤ Example : Variable scope within function;

<script>
   function display()
     {
       var a =10;
       console.log("Inside function : "+a);
     }
     display();
    // Uncaught ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Using var keyword, If you declare variable inside the block{ } statement, the variable can be accessed from outside the block.

 ➤ Example : Variable scope within block;

    Variables declared with the var keyword are not Block Scope.

<script>
  var age = 22;
  if (age > 21)
    {
      var name ="Ankaj Gupta";
      console.log("Inside block, name : ",name);
    }
    console.log("Outside block : ",name);   //name visible on here
</script>

# Variable Hoisting :

Variables declared with var are hoisted to the top of the enclosing function scope. If the variable is accessed before variable declaration, it evaluates to undefined.

Let's try to create an exaple :

 ➤ Example :

    Variables declared with var keyword are hoisted.

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of var keyword in JavaScript :

  • Variable use without initialization : The var statement creates and initializes variables inside the scope. If you don't assign variables value at the declaration time, By default JavaScript automatically a assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    var name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with the var keyword are not Block Scope.

 ➤ Example :

<script>
    for(var i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //Output :6
</script>
  • Variable Re-declaration : You can declare the same variable more than one time and also can be updated/modified.

 ➤ Example : Redeclaration of variable;

<script>
    var fruitsName = 'Apple';
    var fruitsName = 'Mango';
    console.log(fruitsName); //Output : Mango
</script>
  • Variable value Re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    var x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with var keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    var myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>
  • When using var local scope is within a function, means that a variable with the same name can be used in two separate functions, because each is recognized only by the function in which it is declared.

 ➤ Example :

<script>
    function myFunction()
     {
       var data = "I am local scope";
       document.write(data); //Output: I am local scope
     }
    function display()
     {
       var data = "I am  also local scope";
       document.write(data); //Output: I am also local scope
     }
    myFunction();
    display();
</script>
JavaScript
Read