JavaScript: Variables

Table of Contents

Prompt a message

prompt: instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog.

prompt("message");

To save the information inside a variable:

var variableName = variableValue;
var variableName = "variableValue";

Save user input inside a variable

var yourName = prompt("message");

Write strings with variables

alert("Hello " + yourName + ", My name is " + myName);

Challenge

Switch variables aand b:

My solution:

function test() {
 var a = "3";
 var b = "8";
 
 //
 var c = "3";
  var a = "8";
  var b = c;
 //
 
 console.log("a is" + a);
 console.log("b is" + b);
}

Teacher solution:

function test() {
 var a = "3";
 var b = "8";
 
 //
 var c = a;
  a = b;
  b = c;
 //
 
 console.log("a is" + a);
 console.log("b is" + b);
}