Javascript básico

Variables

var myName = 'Arya';
console.log(myName);
// Output: Arya

let meal = 'Enchiladas';
console.log(meal); 
// Output: Enchiladas

const myName = 'Gilberto';
console.log(myName); 
// Output: Gilberto

// Puedes inicializar una variable con var/let sin asignarle valor.

Operaciones típicas

let x = 20;
x -= 5; // Can be written as x = x - 5
console.log(x); // Output: 15

let y = 50;
y *= 2; // Can be written as y = y * 2
console.log(y); // Output: 100

let z = 8;
z /= 2; // Can be written as z = z / 2
console.log(z); // Output: 4


let a = 10;
a++;
console.log(a); // Output: 11


const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.

Comprobar el tipo

const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string

const unknown2 = 10;
console.log(typeof unknown2); // Output: number

const unknown3 = true; 
console.log(typeof unknown3); // Output: boolean

Condicionales

if (true) {
  console.log('This message will print!'); 
}


if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}


isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

// If - Else If - Else:

let stopLight = 'yellow';

if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

// Cases:

let groceryItem = 'papaya';

switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}
  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is equal to: ===
  • Is not equal to: !==
  • the and operator (&&)
  • the or operator (||)
  • the not operator, otherwise known as the bang operator (!)