JavaScript Example

This is example JavaScript code showing some of the basics of the language. This is intended for people who already know things like variables, if statements, and loops in another language.

You need to open your browser’s console to see the code do anything. You can also type JavaScript commands into the console to call functions and check variable values.

<p>Open the console: Control + Shift + I, or F12</p>

<script>
	//print
	console.log('Hello World!');

	//declare variable
	let x = 7;

	// if/else
	if (x > 5){
		console.log("x is more than 5.");
	}
	else {
		console.log("x is NOT more than 5.");
	}

	// while loop
	while (x <= 1000){
		x = x * 2;
		console.log(x);
	}

	// for loops in C style languages
	for (let i=0; i < 6; i++){
		console.log("i is " + i);
	}

	// while loop equivalent to the for loop
	let i = 0;
	while (i < 6){
		console.log("i is " + i);
		i++;
	}

	// array
	let things = ["dog", "cat"];
        // in the console, try things[0]

	// object
	let prices = {"candy bar": 2.5, "pop": 2.99}
        // in the console, try prices["pop"]

	// function
	function area(r){
		a = 3.1416*r**2;
		return a;
	}
        // in the console, try area(2.3);

</script>