Skip to main content

What are the data types and variables in JavaScript? and example of sum operation on hindi variables.




Datatypes in JavaScript

There are majorly two types of languages. First, one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. Example: C, C++, Java. 

// Java(Statically typed)
int x = 5  // variable x is of type int and it will not store any other type.
string y = 'abc' // type string and will only accept string values

Other, Dynamically typed languages: These languages can receive different data types over time. For example- Ruby, Python, JavaScript etc.

// Javascript(Dynamically typed)
var x = 5; // can store an integer
var name = 'string'; // can also store a string.


JavaScript is a dynamically typed (also called loosely typed) scripting language. That is, in JavaScript variables can receive different data types over time. Datatypes are basically typed data that can be used and manipulated in a program.
The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are Primitive(predefined). 
 

  • Numbers: 5, 6.5, 7 etc.
  • String: “Hello” etc.
  • Boolean: Represent a logical entity and can have two values: true or false.
  • Null: This type has only one value : null.
  • Undefined: A variable that has not been assigned a value is undefined.
  • Object: It is the most important data-type and forms the building blocks for modern JavaScript. 

 Variables in JavaScript:

Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. 
 

  • The value stored in a variable can be changed during program execution.
  • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
  • In JavaScript, all the variables must be declared before they can be used.

Before ES2015, JavaScript variables were solely declared using the var keyword followed by the name of the variable and semi-colon. Below is the syntax to create variables in JavaScript:
 

var var_name;
var x;

The var_name is the name of the variable which should be defined by the user and should be unique. These types of names are also known as identifiers


We can initialize the variables either at the time of declaration or also later when we want to use them. Below are some examples of declaring and initializing variables in JavaScript: 
 

// declaring single variable
var name;

// declaring multiple variables
var name, title, num;

// initializng variables
var name = "Harsh";
name = "Rakesh";

JavaScript is also known as untyped language. This means, that once a variable is created in JavaScript using the keyword var, we can store any type of value in this variable supported by JavaScript. Below is the example for this: 
 

// creating variable to store a number
var num = 5;

// store string in the variable num
num = "Hello";

The above example executes well without any error in JavaScript, unlike other programming languages. 


After ES2015, we now have two new variable containers: let and const. Now we shall look at both of them one by one. The variable type Let shares lots of similarities with var but unlike var, it has scope constraints. To know more about them visit let vs var. Let’s make use of the let variable: 
 

// let variable
let x; // undefined
let name = 'Mukund';

// can also declare multiple values
let a=1,b=2,c=3;

// assignment
let a = 3;
a = 4; // works same as var.

Const is another variable type assigned to data whose value cannot and will not change throughout the script.
 

// const variable
const name = 'Mukund';
name = 'Mayank'; // will give Assignment to constant variable error.

 


Most of the time, a JavaScript application needs to work with information. Here are two examples:

  1. An online shop – the information might include goods being sold and a shopping cart.
  2. A chat application – the information might include users, messages, and much more.
We can use variables to store goodies, visitors, and other data.

A real-life Example

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely named sticker on it.

For instance, the variable message can be imagined as a box labeled "message" with the value "Hello!" init:



We can put any value in the box.

We can also change it as many times as we want:


let message; message = 'Hello!'; message = 'World!'; // value changed alert(message);


When the value is changed, the old data is removed from the variable:

let hello = 'Hello world!'; let message; // copy 'Hello world' from hello into message message = hello; // now two variables hold the same data alert(hello); // Hello world! alert(message); // Hello world!

Declaring twice triggers an error

A variable should be declared only once.

A repeated declaration of the same variable is an error:

let message = "This"; // repeated 'let' leads to an error let message = "That"; // SyntaxError: 'message' has already been declared


So, we should declare a variable once and then refer to it without let.

Variable naming

There are two limitations on variable names in JavaScript:

  1. The name must contain only letters, digits, or the symbols $ and _.
  2. The first character must not be a digit.

Examples of valid names:

let userName; let test123;


When the name contains multiple words, camelCase is commonly used. That is: words go one after another, each word except first starting with a capital letter: myVeryLongName.

What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.

These names are valid:


let $ = 1; // declared a variable with the name "$" let _ = 2; // and now a variable with the name "_" alert($ + _); // 3



Examples of incorrect variable names:

let 1a; // cannot start with a digit let my-name; // hyphens '-' aren't allowed in the name


Case matters

Variables named apple and AppLE are two different variables.


Reserved names

There is a list of reserved words, which cannot be used as variable names because they are used by the language itself.

For example: letclassreturn, and are reserved.

The code below gives a syntax error:

let let = 5; // can't name a variable "let", error! let return = 5; // also can't name it "return", error!



Constants

To declare a constant (unchanging) variable, use const instead of let:

const myBirthday = '18.04.1982';


Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so would cause an error:

const myBirthday = '18.04.1982'; myBirthday = '01.01.2001'; // error, can't reassign the constant!

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and clearly communicate that fact to everyone.

Uppercase constants

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in the so-called “web” (hexadecimal) format:

const COLOR_RED = "#F00"; const COLOR_GREEN = "#0F0"; const COLOR_BLUE = "#00F"; const COLOR_ORANGE = "#FF7F00"; // ...when we need to pick a color let color = COLOR_ORANGE; alert(color); // #FF7F00


Benefits:

  • COLOR_ORANGE is much easier to remember than "#FF7F00".
  • It is much easier to mistype "#FF7F00" than COLOR_ORANGE.
  • When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00.

Variables Summary

We can declare variables to store data by using the varlet, or const keywords.

  • let – is a modern variable declaration.
  • var – is an old-school variable declaration. Normally we don’t use it at all.
  • const – is like let, but the value of the variable can’t be changed.

Example of sum operation on hindi language variables:


let ए = 10
let बी = 10
सी = ए + बी;

Comments

Popular posts from this blog

How to get the CPU temperature using ADB?

import os # Function to get the CPU temperature using ADB def get_cpu_temperature():     try:         # Run the ADB command and redirect the output to a temporary file         os.system("adb shell cat /sys/class/thermal/thermal_zone0/temp > temp.txt")         # Read the temperature from the temporary file and convert to Celsius         with open("temp.txt", "r") as file:             temperature = int(file.read().strip()) / 1000.0             return temperature     except Exception as e:         print("Error:", e)         return None     finally:         # Remove the temporary file         os.remove("temp.txt") # Function to check temperature and trigger alarm if necessary def check_temperature_and_notify(threshold):     temperat...

How to call API in angular & with an example of PHP API

How to call API in angular & with an example of PHP API . Software required:- Node ->  https://nodejs.org/en/download/ VS Code ->  https://code.visualstudio.com/download Angular CLI -> npm install - g @angular / cli To understand how to call API in angular follow the below steps:- Step:1 Project Setup 1. Create a project in angular ->  ng new project name 2. Install npm -> npm i 3. Import HttpClientModule in app.module.ts -> import { HttpClientModule } from '@angular/common/http' ; 4. Add provider providers : [ WebserviceService ], example -> ng new crudInAngularPHP Step:2 API Service 1. Create a service with name webservice -> ng g s services/webservice 2. import modules import { HttpClient, HttpHeaders, HttpRequest, HttpEvent } from '@angular/common/http'; 3 .    C all constructor  constructor( private http: HttpClient) 4. Add a common function to get a response of API with name postRequest:-      ...

What is JavaScript? Why JavaScript? How to use javascript?

 WWH JavaScript Watch here with full example and with github:  Watch Now 1. Question. What is JavaScript? Answer :- Javascript is a scripting language. And it's basically used to make web pages more user-friendly and more interactive.     Few Important points related to javascript:- JavaScript is an untyped language.(What does it mean?) Unlike c/java or other programming languages, you don't need to define/declare type of variables JavaScript is an interpreted language.(Means?) Programs written in c/c+ or java, you need to compile first and after that, u can get output. but codes/programs written in javascript will give you output without compilation process. 2. Question. Why JavaScript?  Answer:- Javascript is basically used to make web pages more authentic. For example, you have a signup form of a user and there is a Pincode input box and you want to get the city on the input of pin code so you can add this functionality into your web page with the help of jav...