2.variables and Datatypes in Javascript
2.variables and Datatypes in Javascript
Variables in JavaScript are used to store data values. You can think of them as
containers that hold different types of information. To declare a variable in
JavaScript, you can use the `var`, `let`, or `const` keywords.
1. **`var` :**
- `var` was traditionally used for variable declaration, but it has some scope
issues and is less commonly used now.
```jsx
var age = 19; // Declaring a variable 'age' and assigning it a value of 19
age = 20; // You can change the value of a 'var' variable
```
2. **`let`:**
- `let` allows you to declare block-scoped variables, which means they are only
- accessible within the block (e.g., inside a function or loop) where they are
defined.
```jsx
let name = "Ganta Mukesh";
let age = 19;
```
3. **`const`:**
- `const` is used to declare constants. Once a value is assigned to a `const`,
it cannot be changed.
```jsx
const pi = 3.14159;
```
JavaScript has several data types to represent different kinds of values. These
data types include:
1. **Primitive Data Types:**
a. **String:**
```jsx
let name = "Dodagatta Nihar";
```
b. **Number:**
```jsx
let age = 19;
let price = 19.69;
```
c. **Boolean:**
```jsx
let isStudent = true;
let isAdmin = false;
```
d. **Undefined:**
- Represents a variable that has been declared but hasn't been assigned a
value.
```jsx
let x;
console.log(x); // This will output 'undefined'
```
e. **Null:**
```jsx
let emptyValue = null;
```
a. **Object:**
- Used to store collections of key-value pairs. Objects are created using curly
braces `{}`.
```jsx
let person = {
name: "Bob",
age: 30,
};
```
b. **Array:**
- Used to store ordered collections of values. Arrays are created using square
brackets `[]`.
let colors = ["red", "green", "blue"];
**Function:**
- Functions are objects and can be assigned to variables, passed as arguments, and
returned from other functions.
```jsx
function greet(name) {
return `Hello, ${name}!`;
}
```
These are the fundamental concepts of variables and data types in JavaScript.
Understanding these concepts is essential for writing effective and flexible
JavaScript code.