# JavaScript basics
# Variables and values
Use const by default, let when a binding must be reassigned, and avoid new uses of var:
const course = 'frontend';
let lesson = 2;
lesson += 1;
var legacyName = 'old style';
JavaScript has primitive values such as strings, numbers, booleans, null, undefined, bigint, and symbols. Objects and arrays are reference values:
const name = 'Ada';
const score = 42;
const active = true;
const student = { name, score };
const scores = [42, 98];
console.log(typeof name, typeof student, Array.isArray(scores));
typeof null is a historical language quirk and returns "object"; use value === null when checking for null.
# Expressions and control flow
Template literals interpolate values:
const message = `Student: ${student.name}, score: ${student.score}`;
Use strict equality unless coercion is intentional:
0 == false // true: coercion
0 === false // false: different types
Conditions use truthiness. Be careful with 0, '', false, null, and undefined when an actual value may be missing.
if (scores.length > 0) {
for (const score of scores) {
console.log(score);
}
} else {
console.log('No scores');
}
Errors can be handled at a boundary:
try {
JSON.parse('{bad json}');
} catch (error) {
console.error('Could not read data', error);
}
# Scope
let and const are block-scoped; a binding created inside { ... } is not available outside it. var is function-scoped, which is one reason old loop and callback code can behave unexpectedly. Closures and per-iteration bindings are covered in Functions and closures.
# Exercise
Write a validateName(value) function that returns true only for a non-empty string after trimming. Test it with values from a form without using a framework.