Showing posts with label Javascript for Salesforce. Show all posts
Showing posts with label Javascript for Salesforce. Show all posts

Saturday, March 30, 2024

Explain Javascript Async/Await?

"async and await make promises easier to write". async makes a function return a Promise while await makes a function wait for a Promise

Async Syntax:

The keyword async before a function makes the function return a promise:

Example:

async function myFunction() {

  return "Hello";

}

The above is the same as below:

function myFunction() {

  return Promise.resolve("Hello");

}

Await Syntax:

The await keyword can only be used inside an async function.

The await keyword makes the function pause the execution and wait for a resolved promise before it continues:

let value = await promise;

Let us understand this with an example,

function myFunction(some) {

  console.log('Inside myFunction');

}

async function promiseDemonstration(){

let myPromise = new Promise(function(myResolve, myReject) {

   let x = 0;

  if (x == 0) {

    myResolve("OK");

    console.log('Inside If');

    setTimeout(myFunction , 3000);

  } else {

    console.log('Inside else');

    myReject("Error");

  }

});

let value = await myPromise;

console.log('Awaiting Promise'+value);

myPromise.then(

  function(value) {

    console.log('Inside Value');

    myFunction(value);},

  function(error) {

    console.log('Inside Error');

    myFunction(error);}

);

}

promiseDemonstration();

Explain JavaScript Promise Object?

As we have seen earlier, With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel.

But, asynchronus programmes are difficult to write and difficult to debug.

Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.

A Promise contains both the producing code and calls to the consuming code:

Promise Syntax:

let myPromise = new Promise(function(myResolve, myReject) {

// "Producing Code" (May take some time)

  myResolve(); // when successful

  myReject();  // when error

});

// "Consuming Code" (Must wait for a fulfilled Promise)

myPromise.then(

  function(value) { /* code if successful */ },

  function(error) { /* code if some error */ }

);

When the producing code obtains the result, it should call one of the two callbacks:

When     Call

Success     myResolve(result value)

Error     myReject(error object)

Promise Object Properties:

A JavaScript Promise object can be:

Pending

Fulfilled

Rejected

The Promise object supports two properties: state and result.

While a Promise object is "pending" (working), the result is undefined.

When a Promise object is "fulfilled", the result is a value.

When a Promise object is "rejected", the result is an error object.

myPromise.state      myPromise.result

"pending"      undefined

"fulfilled"      a result value

"rejected"      an error object

Let us understand the use of Promise with an example:

function displayValue(some) {

 console.log('Inside displayValue');

}

let myPromise = new Promise(function(myResolve, myReject) {

  let x = 0;

// The producing code (this may take some time)

  if (x == 0) {

    myResolve("OK");

  } else {

    myReject("Error");

  }

});

myPromise.then(

  function(value) {displayValue(value);},

  function(error) {displayValue(error);}

);

Output:

Inside displayValue


Let us understand the use of Promise with setTimeout.

Example Using Callback:

setTimeout( myFunction, 1000);

function myFunction() {

  console.log('Inside myFunction');

}

Output:

Inside myFunction

Example Using Promise:

function myFunction(some) {

  console.log('Inside myFunction');

}

let myPromise = new Promise(function(myResolve, myReject) {

   let x = 1;

  if (x == 1) {

    myResolve("OK");

    console.log('Inside If');

    setTimeout(myFunction , 3000);

  } else {

    console.log('Inside else');

    myReject("Error");

  }

});

myPromise.then(

  function(value) {

    console.log('Inside Value');

    myFunction(value);},

  function(error) {

    console.log('Inside Error');

    myFunction(error);}

);

Output:

Inside If
Inside Value
Inside myFunction

What are classes in Javascript and explain Inheritance?

A JavaScript class is not an object. It is a template for JavaScript objects. Use the keyword class to create a class. 

Always add a method named constructor().

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

The example above creates a class named "Employee".

The class has two initial properties: "name" and "department".

The example below uses the Employee class to create a Employee object.

const myEmp = new Employee("Farukh", IT);

The constructor method is called automatically when a new object is created. The constructor method is a special method.

It has to have the exact name "constructor".

Sample Example to demonstrate class use:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

  }

}

const myEmp = new Employee("Farukh", "IT");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

Class Inheritance:

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

class Manager extends Employee {

  constructor(name, department, position) {

    super(name, department);

    this.position = position;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

    console.log('position is '+this.position);

  }

}

const myEmp = new Manager("Farukh", "IT", "Consultant");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

position is Consultant

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

Explain JavaScript Callbacks?

 A callback is a function passed as an argument to another function.

In the below example, we can see we are passing displayValue function as an argument to doSum function while calling doSum function.

doSum(2, 3, displayValue);

function displayValue(sum) {

  console.log('callback function called');

  console.log('Sum is '+sum);

}

function doSum(num1, num2, sampleCallbackDemonstration) {

  let sum = num1 + num2;

  sampleCallbackDemonstration(sum);

}

Output:

callback function called

Sum is 5

Note: When you pass a function as an argument, remember not to use parenthesis.

When to Use a Callback?

They above example is to understand the callback syntax.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function like waiting for a file to load.

In the real world, callbacks are most often used with asynchronous functions.

A typical example is JavaScript setTimeout().

setTimeout(myFunction, 3000);

function myFunction() {

  // some code here

}

In the example above, myFunction is used as a callback.

myFunction is passed to setTimeout() as an argument.

3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.

With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel. But, asynchronus programmes are difficult to write and difficult to debug.Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.

What is Javascript Object and Object Methods?

Javascript Object:

As we have already learned that JavaScript variables are containers for data values.

The below code assigns a simple value (Mumbai) to a variable named text:

let text="Mumbai";

Objects are variables too. But objects can contain many values.

The below code assigns many values (Mumbai, Maharashtra, India) to a variable named text:

const text = {name:"Mumbai", state:"Maharashtra", country:"India"};

a) object are used to store collections of data and more complex entities.

b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.

c) Creating an empty object,

let studentDetail = {};

let studentDetail = new Object();

d) Creating an object with properties,

let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"

};

e) To access the property values use dot notation or array notation in case of space in key name as shown below,

studentDetail.name  // dot notation

To access full name use array notation as it has space.

studentDetail[Full Name]   // array notation

f) Adding a value to property,

studentDetail.department = 'Computer Science';

g) We may add comma to last property as shown below.

let studentDetail = {

name: "Test",

rollNo: 1,

};

h) To access the keys use,

Object.keys(studentDetail)

i) Use JSON.stringify to convert object to string

var jsonStrng= JSON.stringify(studentDetail);

console.log(jsonStrng);

"{"name":"Test","rollNo":1,"Full Name":"Test User"}"

j) Use JSON.parse to convert string to object

Object = JSON.parse(jsonStrng);

{name: "Test", rollNo: 1, Full Name: "Test User"}

Object Methods:

An object method is an object property containing a function definition.

const person = {

  firstName: "Farukh",

  lastName: "Haider",

  fullName: function() {

    return this.firstName + " "  + this.lastName;

  }

};

console.log(person.fullName());

Output:

Farukh Haider

How to Access JavaScript Object Properties?

The syntax for accessing the property of an object is:

objectName.property

objectName["property"] 

Let us understand this with an example?

const person = {

  fname:" John",

  lname:" Doe",

  age: 25

};

console.log('person'+person.fname);

console.log('person'+person["fname"]);

Output:

person John

person John

We can also iterate over object as shown below:

for (let x in person) {

  console.log(person[x]);

}

Output:

John

Doe

25

What are basic string methods in Javascript?

 Below are string methods in Javascript. They produces a new string without altering the original string.

String length

String charAt()

String charCodeAt()

String at()

String [ ]

String slice()

String substring()

String substr()

String toUpperCase()

String toLowerCase()

String concat()

String trim()

String trimStart()

String trimEnd()

String padStart()

String padEnd()

String repeat()

String replace()

String replaceAll()

String split()

Let us explore some methods with an example.

JavaScript String Length:

The length property returns the length of a string.

let text = "Farukh";

console.log('text.length '+text.length);

Output:

text.length 6

JavaScript String charAt():

The charAt() method returns the character at a specified index in a string.

let text = "Farukh";

console.log('Result:'+text.charAt(0));

Output:

Result:F

JavaScript String slice():

slice() extracts a part of a string and returns the extracted part in a new string. This method takes 2 parameters:

start position, and end position.

Note: end position is not included .If a parameter is negative, the position is counted from the end of the string:

let text = "Farukh Haider";

console.log('Result:'+text.slice(3, 7));

Output:

Result:ukh 

JavaScript String substring():

substring() is similar to slice().

The difference is that start and end values less than 0 are treated as 0 in substring().

let text = "Farukh Haider";

console.log('Result:'+text.substring(7, 12));

Output:

Result:Haide

JavaScript String toUpperCase(), JavaScript String toLowerCase():

let text = "Farukh Haider";

console.log('Result:'+text.toUpperCase());

console.log('Result2:'+text.toLowerCase());

Output:

Result:FARUKH HAIDER

Result:farukh haider

JavaScript String concat():

concat() joins two or more strings as shown in below example.

let text1 = "Farukh";

let text2 = "Haider";

console.log('Result:'+text1.concat(" ",text2));

Output:

Result:Farukh Haider

What are operators in Javascript?

 Javascript operators are used to perform different types of mathematical and logical computations.

Sample example to demontrate addition, substraction, division:

let x = 5;

let y = 2;

let a = x + y;

let b = x - y;

let c = x / y;

console.log(a);

console.log(b);

console.log(c);

Output:

7

3

2.5

JavaScript Assignment Operators:

The Addition Assignment Operator (+=) adds a value to a variable. Similarly, you can use the other operators as shown below.

let x = 10;

x += 5;

console.log(x);

Output:

15

The += assignment operator can also be used to add (concatenate) strings:

let text1 = "My Name is ";

text1 += "Farukh";

console.log(text1);

Output:

My Name is Farukh

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

JavaScript Comparison Operators:

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

Logical Operators:

Logical operators are used to determine the logic between variables or values.

let x = 6;

let y = 3;

let a = 6;

let b = 6;

if((x < 10 && y > 1))

{

  console.log('Yes satisfied');

}

if((x < 10 || y > 1))

{

  console.log('Yes satisfied');

}

if(!(a == b))

{

    console.log('Yes satisfied');

}

else{

  console.log('Not satisfied');

}

Output:

Yes satisfied

Yes satisfied

Not satisfied

What is the difference between == and === operator?

The == operator compares the values of two variables after performing type conversion if necessary. On the other hand, the === operator compares the values of two variables without performing type conversion.

const num = 1;

const str = "1";

console.log(num == str); 

console.log(num === str); 

Output:

true

false

Conditional (Ternary) Operator:

let name="Test"

let printValue = (name == "Test") ? "Yes":"No";

console.log(printValue);

Output:

Yes

What are Sets in Javascript?

A JavaScript Set is a collection of unique values of any data type.

How to Create a Set?

You can create a JavaScript Set by:

1) Passing an Array to new Set()

Ex: const fruits = new Set(["apple","orange","mango"]);

2) Create a new Set and use add() to add values

Ex: const fruits = new Set();

fruits.add("apple");

fruits.add("orange");

fruits.add("mango");

3) Create a new Set and use add() to add variables

Ex: const fruits = new Set();

const a = "apple";

const b = "orange";

const c = "mango";

fruits.add(a);

fruits.add(b);

fruits.add(c);

What are avaialble Set methods?

new Set(): Creates a new Set

add(): Adds a new element to the Set

delete(): Removes an element from a Set

has(): Returns true if a value exists

clear(): Removes all elements from a Set

forEach(): Invokes a callback for each element

const fruits = new Set(["apple","orange","mango"]);

fruits.forEach (function(value) {

  let text = "";

  text += value;

  console.log(text);

})

Output:

apple

orange

mango

values(): Returns an Iterator with all the values in a Set

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.values()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple

orange

mango

keys(): Same as values()

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.keys()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple

orange

mango

entries(): Returns an Iterator with the [value,value] pairs from a Set

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.entries()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple,apple

orange,orange

mango,mango

size: Returns the number elements in a Set

const fruits = new Set(["apple","orange","mango"]);

console.log(fruits.size);

Output:

3

What are Maps in Javascript?

A Map in Javascript holds key-value pairs where the keys can be any datatype.

How to Create a Map?

We can create a map as shown below.

a) By passing an Array to new Map()

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

b) Create a Map and use Map.set()

const cities = new Map();

cities.set("Nagpur", "Nag");

cities.set("Mumbai", "Mum");

cities.set("Delhi", "Del");

What are avaialble Map methods?

1) new Map() : Creates a new Map object

2) set() : Sets the value for a key in a Map

ex: cities.set("Kolkata", Kol);

3) get() : Gets the value for a key in a Map

ex: cities.get("Kolkata");

4) clear() : Removes all the elements from a Map

5) delete() : Removes a Map element specified by a key

6) has() : Returns true if a key exists in a Map

7) forEach() : Invokes a callback for each key/value pair in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

cities.forEach (function(value, key) {

  let text = "";

  text += key + ' = ' + value 

  console.log(text);

})

Output:

Nagpur = Nag

Mumbai = Mum

Delhi = Del

8) entries() : Returns an iterator object with the [key, value] pairs in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.entries()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nagpur,Nag

Mumbai,Mum

Delhi,Del

9) keys() : Returns an iterator object with the keys in a Map

// Create a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.keys()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nagpur

Mumbai

Delhi

10) values() : Returns an iterator object of the values in a Map

// Create a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

for (const x of cities.values()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

Nag

Mum

Del

11) size : The size property returns the number of elements in a Map

ex: cities.size

What are setTimeOut and setTimeInterval in Javascript?

JavaScript can be executed in time-intervals. This is called timing events.

The two key methods to use with JavaScript are:

a) setTimeout(function, milliseconds)

Executes a function, after waiting a specified number of milliseconds.

As an example, in the below example myFunction will be called after 1 second.

let myvar=setTimeout(myFunction, 1000);

function myFunction() {

  console.log('myFunction called');

}

b) setInterval(function, milliseconds)

Same as setTimeout(), but repeats the execution of the function continuously.

let myvar=setInterval(myFunction, 1000);

function myFunction() {

  console.log('myFunction called');

}

What is JavaScript Arrow Function?

Arrow functions allow us to write shorter function syntax.

Let us understand this with an example:

Before Arrow function:

function hello() {

  return "Hello World!";

}

console.log(hello());

Output: Hello World!

After Arrow function:

hello = () => {

  return "Hello World!";

}

console.log(hello());

Output: Hello World!

Let us understand with one more example:

Before Arrow function:

let x = myFunction(1, 2);

function myFunction(a, b) {

// Function returns the sum of a and b

  return a + b;

}

console.log('before arrow function ==> '+x);

Output:

before arrow function ==> 3

After Arrow function:

myFunction = (a,b) => {

  return a + b;

}

console.log('after arrow function ==> '+myFunction(2,3));

Output:

after arrow function ==> 5

What are functions in Javascript?

 It is a block of code designed to perform a particular task when called.

Syntax:

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses () which is optional.

function name(parameter1, parameter2, parameter3) {

  // code to be executed

  // return something;

}

Functions often compute a return value. The return value is "returned" back to the "caller".

When JavaScript reaches a return statement, the function will stop executing.

Let us understand with an example.

let x = myFunction(1, 2);

function myFunction(a, b) {

// Function returns the sum of a and b

  return a + b;

}

console.log('sum is ==> '+x);

Output:

sum is ==> 3

What are Arrays in Javascript?

An array is a special variable, which can hold more than one value. Arrays are a special kind of objects, with numbered indexes.

What is the difference between Arrays and Objects?

In JavaScript, arrays use numbered indexes.  

In JavaScript, objects use named indexes.

How to create an array?

You can simply create an array using one of the below approach.

a) Using an array literal is the easiest way to create a JavaScript Array.

const array_name = [item1, item2, etc];   

b) Using the JavaScript Keyword new

const fruits= new Array("Mango", "Apple", "Orange");

Note: Array indexes start with 0.

[0] is the first element, [1] is the second element and [Array.length-1] is last element.

Let us deep dive to learn more about array using a below example:

const fruits= new Array("Mango", "Apple", "Orange");

Accessing Array Elements:

console.log(fruits[0]);

Output: Mango

Changing an Array Element:

fruits[0]="Banana";

console.log(fruits[0]);

Output: Banana

converting an array to String:

console.log(fruits.toString());

Output: Banana,Apple,Orange

Adding Array Elements:

fruits.push("Lemon");

To check if the Javascript object is array, we can use Array.isArray() as shown below:

console.log(Array.isArray(fruits));

Output: True

One way to loop through an array, is using a for loop which we learn in previous blog post.

we can can also use the Array.forEach() function as shown below.

const fruits= new Array("Mango", "Apple", "Orange");

var text="";

fruits.forEach(myFunction);

function myFunction(value) {

  text = text + value + " ";

}

console.log(text);

Output:

Mango Apple Orange

What are different kinds of loops in Javascript?

JavaScript supports different kinds of loops as described below:

  1. for - loops through a block of code a number of times
  2. for/in - loops through the properties of an object
  3. for/of - loops through the values of an iterable object
  4. while - loops through a block of code while a specified condition is true
  5. do/while - also loops through a block of code while a specified condition is true

for loop:

As we know var declaration is globally scoped where as let and const are block  scoped, let us understand the use of var and let in for loop.

var i = 5;

for (var i = 0; i < 10; i++) {

 }

console.log(i);

let j = 5;

for (let j = 0; j < 10; j++) {

}

console.log(j);

Output:

10

5

for in loop:

The JavaScript for in statement loops through the properties of an Object:

for in over object:

The for in loop iterates over a employee object

Each iteration returns a key (x)

The key is used to access the value of the key

The value of the key is employee[x]

const employee = {fname:"Farukh", lname:"Haider"};

let text = "";

for (let x in employee) {

  text += employee[x] + " ";

}

console.log(text);

Output:

Farukh Haider

for in over array:

The for in loop iterates over a number array

Each iteration returns a key (x)

The key is used to access the value of the key

The value of the key is numbers[x]

const numbers = [1, 10, 11, 20];

var sum = 0;

for (let x in numbers) {

  sum += numbers[x] ;

}

console.log(sum);

Output:

42

for of loop:

For/of is not supported in Internet Explorer.

let name = "Farukh";

let text = "";

for (let x of name) {

text += x;

}

console.log(text);

Output:

Farukh

JavaScript While Loop:

The while loop loops through a block of code as long as a specified condition is true.

var i=0;

var text="";

while (i < 2) {

  text += "The number is " + i + " "  ;

  i++;

}

console.log(text);

Output:

The number is 0 The number is 1

The Do While Loop:

This loop will execute the code block once, before checking if the condition is true, then 

it will repeat the loop as long as the condition is true.

var i=0;

var text="";

do {

  text += "The number is " + i;

  i++;

}

while (i < 0);

console.log(text);

Output:

The number is 0

We can also use for forEach() to iterate over Array and Maps as shown below.

forEach() over Array:

const fruits= new Array("Mango", "Apple", "Orange");

var text="";

fruits.forEach(myFunction);

function myFunction(value) {

  text = text + value + " ";

}

console.log(text);

Output:

Mango Apple Orange


forEach() over Map:

forEach() : Invokes a callback for each key/value pair in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

cities.forEach (function(value, key) {

  let text = "";

  text += key + ' = ' + value 

  console.log(text);

})

Output:

Nagpur = Nag

Mumbai = Mum

Tuesday, March 9, 2021

What are data types in Javascript?

 A) Values in Javascript will have a type.

B) There are 8 basic data types in Javascript.

1) String:

let name = 'Test';  

String in Javscript is surrounded by quotes. 

Quotes can single, double quotes.

2) Number:

let n = 10;  // Number

3) Boolean:

let checkName =  true;

let checkData = false;

4) "null":

It contains only null value. 

In Javascript, null is not a reference to a non existing object or null pointer. 

It just represents empty or unknown value.

let a= null;

5) "undefined":

It also represent special type, here the variable is declared but not assigned any value as shown below,

let a;

6) bigint:

Used to store integers value of arbitrary length.

bigint value is created by appending n to the end of an integer.

const = 11111111112222222223333333333344444444n;

7) object:

a) object are used to store collections of data and more complex entities.

b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.

c) Creating an empty object,

let studentDetail = {};

let steudentDetail = new Object();

d) Creating an object with properties,

let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"

};

e) To access the property values use dot notation or array notation in case of space in key name as shown below,

studentDetail.name  // dot notation

To access full name use array notation as it has space.

studentDetail[Full Name]   // array notation

f) Adding a value to property,

studentDetail.department = 'Computer Science';

g) We may add comma to last property as shown below.

let studentDetail = {

name: "Test",

rollNo: 1,

};

h) To access the keys use,

Object.keys(studentDetail)

i) Use JSON.stringify to convert object to string

var jsonStrng= JSON.stringify(studentDetail);

console.log(jsonStrng);

"{"name":"Test","rollNo":1,"Full Name":"Test User"}"

j) Use JSON.parse to convert string to object

Object = JSON.parse(jsonStrng);

{name: "Test", rollNo: 1, Full Name: "Test User"}

k) The below are also different kinds of object in Javascript,

Array

Date

Error

8) symbol:

9) Date Object:

Javascript Date object let us work with dates. They are created with the new Date() constructor.

const d = new Date();

Below are 4 ways to create a new date object:

A) new Date()

The time is adjusted according to timezone the code is running in.

Example:

let now= new Date();

alert( now ); // shows current date/time

Output:

Sun Aug 07 2022 14:40:43 GMT+0530 (India Standard Time)

B) new Date(year, month, day, hours, minutes, seconds, milliseconds)

C) new Date(milliseconds)

D) new Date(date string)

The time is adjusted according to timezone the code is running in.

Example:

let date = new Date("2022-01-01");

alert(date);

Output:

Sat Jan 01 2022 05:30:00 GMT+0530 (India Standard Time)

For accessing the date components below methods are available,

A) getFullYear()

Returns 4 digits.

B) getMonth()

Get the month, Values return are from 0 to 11.

C) getDate()

Get the day of month, Values return are fromfrom 1 to 31.

D) getHours(), getMinutes(), getSeconds(), getMilliseconds()

To get the other corresponding time components.

Similarly we have set Methods as well.

Notes:

1) Date and time in Javascript are represented with the Date object. We cannot create "only date" or "only time".

2) Months are counted from 0 to 11. January is a 0 month.

3) Use Date.now() to get current time stamp.

alert(Date.now());

Timestamps in javascript are in milliseconds and not seconds.

What are variables and constants in Javascript?

JavaScript is cross-platform, object-oriented programming language used for making web pages interactive.

 (A) Variables:

1) Variable are used to store data values. 

2) Variable name contains only letters, digits or the symbol $ and _.

3) Variable name must begins with letter, $ and _ and not with digits.

4) To create variable we use let as shown below,

let name = 'Test';

In older scripts keyword "var" is used.

var name = 'Test';

var declaration is globally scoped where as let and const are block  scoped.

Let's declare var inside block and console it outside the block and see the result.

variables and constants in Javascript

Let's declare let inside block and console it outside the block and see the result.

variables and constants in Javascript

Let's declare let outside block and assign value to it inside block and console it outside the block and see the result.

variables and constants in Javascript


5) We can also declare a variable as shown below without using let, this was mainly possible during old times and this still works unless we don't put "use strict" in our script.

Example:

num = 10;  // will work

Example:

"use strict";

num = 10; // error: num is not defined

6) The information can be of below type,

Number, String, Boolean, Date/Time, Objects etc.


(B) Constants:

1) Constants are unchanging variables.

2) Declare a constant with const keyword.

3) If we are sure that variable will never change its values use const keyword before variable.

4) const  must be initialized during declaration.

Example:

const tDay = '01.01.2000';

Summary:

1) let is a modern variable declaration.

2) var is old school variable declaration.

3) const is similar to let but value of const can't be changed.