1. Home
  2. Docs
  3. Web Technology I
  4. JavaScript-Client Side Sc...
  5. Variables and Data Types

Variables and Data Types

Here is the description of Variables and Data Types:

image 26
let myVariable; // Declaration using let
var anotherVariable; // Declaration using var
const constantVariable = 42; // Declaration using const (immutable)

var:

  • Variables declared with var have function scope or global scope.
  • They can be re-declared within the same function or block.
  • They can be updated.
function exampleVar() {
  var x = 5;
  var x = 10; // Re-declaration is allowed

  if (true) {
    var x = 20; // Updated
  }

  console.log(x); // Output: 20
}

let:

  • Variables declared with let have block scope.
  • They cannot be re-declared in the same scope.
  • They can be updated.
function exampleLet() {
  let y = 5;
  // let y = 10; // Error: Cannot redeclare 'y' in the same scope

  if (true) {
    let y = 20; // Different block scope
    console.log(y); // Output: 20
  }

  console.log(y); // Output: 5
}

const:

  • Variables declared with const have block scope.
  • They cannot be re-declared or updated.
function exampleConst() {
  const z = 5;
  // const z = 10; // Error: Cannot redeclare 'z' in the same scope
  // z = 15; // Error: Cannot update 'z'

  if (true) {
    const z = 20; // Different block scope
    console.log(z); // Output: 20
  }

  console.log(z); // Output: 5
}
image 28
let myVariable = "Hello, World!"; // Initialization with a string
var anotherVariable = 10; // Initialization with a number
image 27
  • Primitive data types
  • Object data types
image 29

  • Object
  • Array
  • Function
  • Date

let person = {
  name: 'John',
  age: 25,
  city: 'New York'
};
let fruits = ['apple', 'banana', 'orange'];
function greet(name) {
  return 'Hello, ' + name + '!';
}
let today = new Date();

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *