JavaScript values refer to the different types of data that can be stored and manipulated in a JavaScript program. These values include primitive data types such as numbers, strings, booleans, null, undefined, symbols, as well as object types such as arrays, functions, and objects. Let's delve into each of these value types with examples.
1. Numbers:
Example:
let num2 = 3.14; // Floating-point number
2. Strings:
Example:
let str2 = "World"; // Double quotes
3. Booleans:
Example:
let isTrue = true;
let isFalse = false;
4. Null and Undefined:
Example:
let emptyValue = null;
let undefinedValue;
console.log(undefinedValue); // undefined
5. Symbols:
Example:
const sym1 = Symbol('description');
const sym2 = Symbol('description'); // Different from sym1
6. Arrays:
Example:
let numbers = [1, 2, 3, 4, 5];
let mixedArray = [1, 'hello', true, [6, 7, 8]];
7. Objects:
Example:
let person = {
name: 'Alice',
age: 30,
hobbies: ['reading', 'painting'],
greet: function() {
console.log('Hello!');
}
};
8. Functions:
Example:
function add(a, b) {
return a + b;
}
let result = add(5, 10); // 15
9. Regular Expressions:
Example:
let pattern = /[A-Z]/; // Matches uppercase letters
let emailPattern = /\S+@\S+\.\S+/; // Matches email addresses
10. Dates:
Example:
let currentDate = new Date();
console.log(currentDate); // Current date and time
11. Promises:
Example:
setTimeout(() => {
resolve('Data fetched successfully');
}, 2000);
});
promise.then((data) => {
console.log(data);
});
12. Nullish Coalescing Operator (??):
Example:
let defaultName = username ?? 'Guest';
console.log(defaultName); // Guest
13. BigInt:
Example:
const bigNumber = BigInt(9007199254740991);
console.log(bigNumber); // 9007199254740991n
14. Maps and Sets:
Example:
myMap.set('key1', 'value1');
let mySet = new Set([1, 2, 3, 3, 4, 5]);
console.log(mySet); // Set { 1, 2, 3, 4, 5 }
15. JSON (JavaScript Object Notation):
Example:
let jsonData = '{"name": "John", "age": 30}';
let parsedData = JSON.parse(jsonData);
console.log(parsedData.name); // John
16. Template Literals:
Example:
let greeting = `Hello, ${name}!
How are you?`;
console.log(greeting);
17. Iterators and Generators:
Example:
let count = 0;
while (true) {
yield count++;
}
}
let counter = countGenerator();
console.log(counter.next().value); // 0
18. ArrayBuffer and Typed Arrays:
Example:
let intArray = new Int32Array(buffer);
intArray[0] = 42;
console.log(intArray); // Int32Array [ 42, 0, 0, 0 ]
19. Proxy Objects:
Example:
let handler = {
get: function(target, prop, receiver) {
return prop in target ? target[prop] : 'Property not found';
}
};
let proxyObj = new Proxy(targetObj, handler);
console.log(proxyObj.name); // Property not found
20. Symbols in Objects:
Example:
const privateProperty = Symbol('private');
let obj = {
[privateProperty]: 'This is a private property'
};
console.log(obj[privateProperty]); // This is a private property
Practice Excercise Practice now