JavaScript Concepts and Programs
1. Explain different data types in JavaScript with suitable examples.
JavaScript supports the following data types:
1. String: Used to represent textual data.
Example: let name = "Alice";
2. Number: Represents both integer and floating-point numbers.
Example: let age = 25;
3. Boolean: Represents logical values - true or false.
Example: let isStudent = true;
4. Undefined: A variable that has been declared but not assigned a value.
Example: let x;
5. Null: Represents an intentional absence of any value.
Example: let x = null;
6. Object: Used to store collections of data.
Example: let person = { name: "John", age: 30 };
7. Symbol: A unique and immutable primitive value used as object keys (ES6).
Example: let sym = Symbol("id");
2. Write a JavaScript program using loops and conditions to print prime numbers between 1
and 100.
To find prime numbers between 1 and 100:
for (let i = 2; i <= 100; i++) {
JavaScript Concepts and Programs
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
if (isPrime) console.log(i);
3. Differentiate between var, let, and const with examples.
1. var:
- Function scoped.
- Can be redeclared and updated.
- Hoisted.
Example: var x = 5;
2. let:
- Block scoped.
- Cannot be redeclared in the same scope.
- Can be updated.
Example: let y = 10;
3. const:
- Block scoped.
- Cannot be redeclared or updated.
Example: const z = 15;
4. Create a function in JavaScript to sort an array of strings alphabetically.
function sortStrings(arr) {
JavaScript Concepts and Programs
return arr.sort();
let fruits = ["banana", "apple", "orange"];
console.log(sortStrings(fruits));
5. What are JavaScript objects? Create a custom object and demonstrate object methods.
JavaScript objects are collections of key-value pairs. They can contain properties and methods.
let car = {
brand: "Toyota",
model: "Corolla",
start: function () {
return `${this.brand} ${this.model} started.`;
};
console.log(car.start());
6. Write a program to demonstrate string operations like slicing, concatenation, and
replacement.
let str = "JavaScript";
console.log(str.slice(0, 4)); // Java
console.log(str + " Tutorial"); // JavaScript Tutorial
console.log(str.replace("Script", "Guide")); // JavaGuide
7. Discuss the role and syntax of comments, statements, and expressions in JavaScript.
Comments:
// Single-line comment
JavaScript Concepts and Programs
/* Multi-line
comment */
Statements:
Instructions executed by the browser.
Example: let x = 5;
Expressions:
Produces a value.
Example: 5 + 3;
8. Design a calculator program that uses functions to perform basic operations.
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
function divide(a, b) {
return b !== 0 ? a / b : "Cannot divide by zero";
console.log(add(10, 5)); // 15
console.log(subtract(10, 5)); // 5
console.log(multiply(10, 5)); // 50
console.log(divide(10, 5)); // 2