Variable and Data Type in JavaScript.

Variable and Data Type in JavaScript.

What is a variable in javascript?

A variable is used to store information or a Variable is used to store data or information.

A variable has a name (the word that you use to refer to the value that the variable contains). A variable also has a data type (which determines the kind of data that the variable can store).

let's declare the variable.

Create a Variable in Javascript using the let keyword.

let message; //declare a variable with name "massage"
message = "Hello"; // store "Hello" in variavle name

console.log(message); // In console you get "Hello" 

//We can also write like this formate.

let message = "Hello";
console.log(message);

We can also declare multiple variables in one line.

Example:

let user = "John", age = 25, city = "Delhi";

but this is not good practice for your coding journey. So don't do it.

Always write multi-line variants. it is a bit longer but easier to read.

Example of multiline variant.

let user = "John";
let age = 20;
let message = "Hello";

console.log(user) // result: John
console.log(age) // result: 20
console.log(message) // result:  Hello

Let's take the analogy of the box to understand the variable.

Imagine a coffee box with a uniquely-named sticker on it.

variable message can be imagined as a box labeled "Nescafe" with the value of "quantity of coffee stored in a box" on it

let nescafe = "coffee";
console(nescafe);

We can put any value in the box. We can also change it as many times as we want.

If the Nescafe box can is empty. We can store anything. like Sugar

Example:

let nescafe = "100gm coffie";
//if nescafe box is empty. we can store sugar.
nescafe = "Sugar";

console.log(nescafe) // result is sugar

We can also declare two variables and copy data from one into the other.

let greet = "Hello world";

let message;
message = greet;      // copy hello world from greet

console.log(greet);   //result Hello world
console.log(message); //Hello world
let nescafe

Declaring twice variable names triggers an error.

Example:

let message = "Jhon";

let message = "Roman";
consol.log(message) // result: syntax error

Note: Repeted let leads to an error. We should declare a variable once and then refer to it without let.

Variable Naming

  1. Use descriptive names: Your variable name should reflect what it represents or what value it holds.

  2. Use camelCase: Start with a lowercase letter and use capital letters for the first letter of each new word. For example, firstname or myVariableName.

  3. Avoid reserved words: You cannot use JavaScript reserved words (such as if, while, for, true, false, etc.) as variable names.

  4. Use only letters, numbers, and underscores: Variable names can only contain letters, numbers, and underscores (_). They cannot contain spaces, hyphens, or special characters.

  5. Use meaningful abbreviations: If you need to use an abbreviation in your variable name, make sure it is meaningful and easy to understand.

  6. Be consistent: Use a consistent naming convention throughout your code.

  7. Use lowercase for constants: If you are defining a constant variable (a variable that will not change), use all lowercase letters and separate words with underscores. For example, const pi = 3.14.

    Note: variable names are case-sensitive, so myVariable and MyVariable is two different variables in JavaScript.

Create a variable using the const keyword.

you can use the const keyword to declare a constant variable. A constant variable is like a regular variable, except that its value cannot be changed once it has been assigned.

Example:

const pi = 3.14;
console.log(pi); // result 3.14

In this example, pi is a constant variable that has been assigned the value of 3.14. If you try to assign a new value to pi, you will get an error:

Example:

const pi = 3.14;
// assign new value to pi.
pi = 3.14159; 
console.log(pi); //// Error: Assignment to constant variable.

Data type:

JavaScript has several built-in data types, which are categorized into two main groups: primitive types and object types.

Primitive type:

Primitive data types are the most basic data types that are not objects. There are five primitive data types in JavaScript: number, string, boolean, undefined, and null.

Number:

The Number type represents both integer and floating-point numbers.

Example:

const num1 = 42; // integer
const num2 = 3.14; // floating-point

String:

The String type represents a sequence of characters.

const str1 = "Hello, World!"; // using a string literal
const str2 = 'Single quotes are also valid'; // using single quotes

In JavaScript, strings are immutable, which means that once a string is created, it cannot be changed. However, you can create a new string based on the original string, by using string methods such as slice(), concat(), or replace().

Example:

const str1 = "Hello, Universe!";

//Create new variable str2 and slice Universe from str1
const str2 = str1.slice(0, 8); // returns "Hello"

//Create str3 and concat str1 + str3;
const str3 = str1.concat(" How are you?"); // returns "Hello, World! How are you?"

//Create str4 and using replace method to replace universe with World.
const str4 = str1.replace("World", "World"); // returns "Hello, World!"

Boolean:

The Boolean type represents a logical value that can be either true or false.

Example:

const bool1 = true; // boolean literal
const bool2 = false; // boolean literal

Undefined:

The Undefined type has only one value, undefined, which represents a variable that has not been initialized or a property that does not exist.

let foo; // undefined

Null:

The Null type has only one value, null, which represents a deliberate non-value or absence of an object value.

const foo = null; // null

Primitive data types in JavaScript are passed by value. When you assign a primitive value to a variable, you are making a copy of that value, so changing the variable does not affect the original value.

Example:

let a = 42;
let b = a;
b = 3.14;
console.log(a); // Output: 42
console.log(b); // Output: 3.14

Non-primitive

Non-primitive data types are objects and functions. Unlike primitive data types, non-primitive data types are mutable, which means that their values can be changed.

Object:

An Object is a collection of key-value pairs, where each key is a string (or symbol) and each value can be any data type, including other objects or functions. Objects are created using object literals ({}).

const obj1 = { 
// name is property and John is value.
  name: "John",
  age: 30,
  city: "New Delhi"
  };
console.log(obj1);

//We can add another property in (obj1). I want to add  property gender.
obj1.gender = "Male";

// we can also delete any property form object. example I want to remove age property form obj1.

delete obj1.age;

Array:

An array is a special type of object that stores an ordered list of values, which can be of any data type. Arrays are one of the most commonly used data structures in JavaScript.

Example:

const arr1 = [1, 2, 3]; // using an array literal
console.log(arr1);

Arrays in JavaScript are zero-indexed, which means that the first element has an index of 0, the second element has an index of 1, and so on. You can access individual elements in an array using bracket notation.

Example:

const arr1 = [1, 2, 3];
const firstElement = arr1[0]; // returns 1
const secondElement = arr1[1]; // returns 2

You can also change the value of an element in an array by assigning a new value to its corresponding index.

const arr1 = [1, 2, 3];
arr1[1] = 4; // changes the second element to 4
console.log(arr1); // Output: [1, 4, 3]

Arrays have several built-in methods that allow you to manipulate the contents of the array. Here are some common array methods:

  • push(): adds one or more elements to the end of the array.

  • pop(): removes the last element from the array and returns it.

  • shift(): removes the first element from the array and returns it.

  • unshift(): adds one or more elements to the beginning of the array.

  • slice(): returns a new array containing a portion of the original array.

  • splice(): changes the contents of an array by removing or replacing existing elements and/or adding new elements.

Arrays in JavaScript can also be nested, which means that an array can contain other arrays:

Example:

  •   const nestedArray = [[1, 2], [3, 4, 5], [6]];
      const secondElementOfFirstArray = nestedArray[0][1]; // returns 2
    

Thank You