Basic Programming Concepts in JavaScript

What is a program?

(One informal definition:)
A series of instructions in some programming language. Each instruction asks the computer to do one thing. Instructions are read from top to bottom, one at a time.

Some basic concepts for today:

  • Input
  • Output
  • Processing, calculation
  • Writing new code
  • Using existing pieces (functions)
  • Variables
  • Strings, numbers

Actual Order:

  • Output
  • Using existing pieces (functions)
  • Strings, numbers
  • Processing, calculation
  • Writing new code
  • Variables
  • Input

Output a string, using a function:

alert("hello world");
Notes: alert is a built-in function that will put up a dialog box with some text. You need to give it that text as a string in parentheses. All function calls need parentheses, even if there is nothing in them.

Programming languages are very picky about syntax! What happens if we type:

    alert(hello world);

Output the result of a calculation:

alert(5 + 7);
alert("hello" + "world");
alert("hello " + "world");
alert("hello" + " " + "world");
Notes: alert can take a string or a number. The + symbol works with numbers (addition) or strings (concatenation).

What happens if we type:

    alert("5 + 7");
    alert("5" + "7");
    alert("5" + 7);
    alert(5 + "7");

Using variables in new code:

Think of variables as places to store information. A variable has a name, and it has a value (i.e., the content being stored). We set or change the value using assignment.

var myMessage = "hello world";
myMessage = "a new message";
alert("This is " + myMessage);

var a = 7;
var b = 9;
var c = a + b;

a = "Hello ";
b = "World";
c = a + b;
Notes: The var keyword says that we are introducing a new variable.
Assignment is right to left -- the variable name goes on the left-hand side of the = symbol and the value (or calculation that creates a value) goes on the right.

Getting input:

var personsName = prompt("Please enter your name");
var num1 = prompt("Please enter a number");
var num2 = prompt("Please enter a number");
alert(num1 + num2);
var numericNum1 = parseFloat(num1);
var numericNum2 = parseFloat(num2);
alert("Added as numbers: " + (numericNum1 + numericNum2));
Notes: prompt is a built-in function that prompts for a value. It always takes it as a string value. If the input was a number, convert it from a string to the number using the build-in parseFloat function. variable.