Skip to main content

Command Palette

Search for a command to run...

Day 2: Variables and Data Types in JavaScript

Published
2 min read
Day 2: Variables and Data Types in JavaScript

Welcome back to our JavaScript series! Today, we'll learn about variables and data types, which are fundamental concepts in programming.

Variables

Variables are like containers that store data values. In JavaScript, you can declare a variable using var, let, or const.

  1. var: This keyword is used to declare a variable. However, it's not commonly used anymore due to some issues with its scope.

     var name = 'Alice';
     console.log(name); // Output: Alice
    
  2. let: This keyword is preferred for declaring variables that can be reassigned.

     let age = 25;
     age = 26;
     console.log(age); // Output: 26
    
  3. const: This keyword is used for variables that should not change. Once a value is assigned to a const variable, it cannot be reassigned.

     const pi = 3.14;
     console.log(pi); // Output: 3.14
    

Data Types

JavaScript has several data types. The most commonly used ones are:

  1. String: Represents text. Strings are written inside quotes (' '/" ").

     let greeting = 'Hello, World!';
     console.log(greeting); // Output: Hello, World!
    
  2. Number: Represents numbers. It can be integers or decimals.

     let score = 95;
     let temperature = 36.5;
     console.log(score); // Output: 95
     console.log(temperature); // Output: 36.5
    
  3. Boolean: Represents true or false values.

     let isJavaScriptFun = true;
     console.log(isJavaScriptFun); // Output: true
    
  4. Null: Represents the intentional absence of any object value.

     let emptyValue = null;
     console.log(emptyValue); // Output: null
    
  5. Undefined: Represents a variable that has been declared but not yet assigned a value.

     let notAssigned;
     console.log(notAssigned); // Output: undefined
    
  6. Object: Represents a collection of properties. Objects are written in curly braces {}.

     let person = {
         name: 'Bob',
         age: 30
     };
     console.log(person); // Output: { name: 'Bob', age: 30 }
    

Type Conversion

Sometimes, you might need to convert one data type to another. JavaScript can do this automatically (Implicit Type Casting), but you can also do it manually (Explicit Type Casting).

  1. String to Number:

     let str = '123';
     let num = Number(str);
     console.log(num); // Output: 123
    
  2. Number to String:

     let num = 123;
     let str = String(num);
     console.log(str); // Output: '123'
    

Summary

Today, we covered variables and data types in JavaScript. Variables are used to store data, and JavaScript has different data types to represent different kinds of information. Tomorrow, we'll dive into operators and expressions.

More from this blog

Mohit's blog

51 posts