vanilla javascript
- User
vanilla javascript
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
vanilla javascript
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Vanilla JavaScript refers to using plain JavaScript without any additional libraries or frameworks like React, Vue, or jQuery. Here's a comprehensive overview:
// Variables (let, const, var)
let count = 0; // Block-scoped, reassignable
const PI = 3.14159; // Block-scoped, not reassignable
var oldSchool = true; // Function-scoped (avoid when possible)
// Primitive types
let num = 42; // Number
let text = "Hello"; // String
let isActive = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
let uniqueId = Symbol('id'); // Symbol
let bigNum = 9007199254740991n; // BigInt
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const sayBye = function(name) {
return `Goodbye, ${name}`;
};
// Arrow function
const multiply = (a, b) => a * b;
// Immediately Invoked Function Expression (IIFE)
(function() {
console.log("I run immediately!");
})();
// Objects
const user = {
name: "Alice",
age: 30,
isAdmin: false,
greet() {
return `Hi, I'm ${this.name}`;
}
};
// Accessing properties
console.log(user.name); // Dot notation
console.log(user["age"]); // Bracket notation
// Arrays
const fruits = ["apple", "banana", "cherry"];
fruits.push("date"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("apricot"); // Add to beginning
fruits.shift(); // Remove from beginning
// Conditionals
if (count > 10) {
console.log("Greater than 10");
} else if (count > 5) {
console.log("Between 6 and 10");
} else {
console.log("5 or less");
}
// Ternary operator
const status = age >= 18 ? "adult" : "minor";
// Switch statement
switch (fruit) {
case "apple":
console.log("Red fruit");
break;
case "banana":
console.log("Yellow fruit");
break;
default:
console.log("Unknown fruit");
}
// Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
for (const fruit of fruits) {
console.log(fruit); // Values in iterable
}
for (const key in user) {
console.log(key, user[key]); // Keys in object
}
// Selecting elements
const heading = document.getElementById("main-title");
const paragraphs = document.querySelectorAll("p");
const buttons = document.getElementsByTagName("button");
const specialItems = document.getElementsByClassName("special");
// Modifying content
heading.textContent = "New Title"; // Text only
heading.innerHTML = "Title with <em>emphasis</em>"; // HTML content
// Changing styles
heading.style.color = "blue";
heading.style.fontSize = "24px";
// Classes
heading.classList.add("highlight");
heading.classList.remove("old-class");
heading.classList.toggle("visible");
heading.classList.contains("highlight"); // true
// Attributes
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
const href = link.getAttribute("href");
link.removeAttribute("target");
// Creating elements
const newPara = document.createElement("p");
newPara.textContent = "I'm a new paragraph";
document.body.appendChild(newPara);
// Event handling
const button = document.querySelector("button");
button.addEventListener("click", function(event) {
console.log("Button clicked!", event);
});
// Event delegation
document.getElementById("parent-list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
console.log("List item clicked:", e.target.textContent);
}
});
// Template literals
const name = "World";
const greeting = `Hello, ${name}!`;
// Destructuring
const { name, age } = user;
const [first, second] = fruits;
// Spread operator
const newArray = [...fruits, "elderberry"];
const updatedUser = { ...user, age: 31 };
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Optional chaining
const city = user?.address?.city;
// Nullish coalescing
const username = user.username ?? "Anonymous";
// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((total, n) => total + n, 0);
const hasNegative = numbers.some(n => n < 0);
const allPositive = numbers.every(n => n > 0);
// Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
// Promises
function fetchUser() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ id: 1, name: "Alice" });
// or reject(new Error("Failed to fetch"));
}, 1000);
});
}
fetchUser()
.then(user => console.log(user))
.catch(error => console.error(error));
// Async/await
async function getUser() {
try {
const response = await fetch('https://api.example.com/users/1');
const user = await response.json();
return user;
} catch (error) {
console.error("Error fetching user:", error);
}
}
// Fetch API
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
// Local Storage (persists after browser close)
localStorage.setItem('username', 'alice');
const username = localStorage.getItem('username');
localStorage.removeItem('username');
localStorage.clear();
// Session Storage (cleared after browser close)
sessionStorage.setItem('tempData', JSON.stringify({id: 123}));
const data = JSON.parse(sessionStorage.getItem('tempData'));
// Cookies
document.cookie = "name=Alice; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
Vanilla JavaScript is powerful on its own and forms the foundation for all JavaScript frameworks. Mastering these basics will make you a more effective developer regardless of which libraries or frameworks you use later.