Type Here to Get Search Results !

Lesson 4: Variables and Constants

Variables and constants are like containers where you store data and values for processing in JavaScript.

The difference between a variable and a constant is this: once you give a value to a constant the value is meant to be kept unchanged throughout the script. In all circumstances where you reasonably foresee that the original value is modified through the script, by all means use a variable as your storage room. In fact, you're going to use variables most of the times.

In this lesson, you're going to learn:
  • how to create variables and constants;
  • how to assign values to variables and constants;
  • how to use variables in your code;
  • how to name variables and constants correctly.

 

How to create variables and constants


You declare, that is, create variables and constants in a similar way.
Here's how you declare a variable:

/*To declare a variable you give it a name preceded by the JavaScript keyword var*/ var amountDue;

In the sample code above you declare a variable named amountDue.

The variable declaration ends with a ( ; ) semicolon, which makes it a self-contained statement.

Also, because JavaScript is case sensitive, every time you refer to the amountDue variable, make sure you keep the letter case exactly the same as the original declaration (this particular notation is called camelCase because it looks like a camel's hunch).

Here's how you declare a constant:

/*To declare a constant you give it a name preceded by the JavaScript keyword const Also take note: const is not supported by Internet Explorer use var instead: it's safer*/ const taxRate;


In the sample code above, you declare a taxRate constant. As you can see, the declaration is very similar to the variable declaration, the only difference being the keyword used: var in the case of a variable and const in the case of a constant.

How to assign values to variables

After you create a variable, you must assign (give) a value to it (or said in Geeeky talk "initialize a variable") . The ( = ) equal sign is called assignment operator: you assign the value of what is on the right side of the = sign to whatever is on the left side of the = sign. Notice: you cannot perform operations with empty variables.

Ready to fire off your text editor? Let's get coding!

Prepare a basic HTML document with the JavaScript code illustrated below:



Did you see the good old alert box displaying the number 10 popping up? If you didn't, make sure your code is typed exactly the same as in the snippet above (Notice: When tracing bugs (errors) in your JavaScript code, look out for brackets, semicolons ( ; ), quotes (' '), and letter casing).

That's great! Try experimenting with the code above. For example, change the value of quantity and productPrice, or just come up with your own variables.

 

How to name variables (and constants)


Choose descriptive names for your variables (var amountDue; rather than var x;): this way your code will be more readable and understandable.

While this can be called good programming practice (but also common sense), there are also syntax rules (yes, just like any natural language) when it comes to naming variables, and they must be obeyed, at least if you want your JavaScript script to work.

Keep an eye on the following simple rules when you name variables:

 

1) The first character must be a letter, an ( _ ) underscore, or a ( $ ) dollar sign:

Illustration:legal var names can be total, _total, $total, but not 5total because it starts with a number.
5total is wrong: var name cannot start with a number

 

2) Each character after the first character can be a letter, an ( _ ) underscore, a ( $ ) dollar sign, or a number:

Illustration:legal var names can be total, to_tal, total$, total5

3) Spaces and special characters other than ( _ ) and $ are not allowed anywhere:

Illustration:total is a legal var name, but not to tal, total#, total£
  • to tal is wrong: spaces are not allowed;
  • total# is wrong: # character is not allowed;
  • total£ is wrong: £ character is not allowed.

 

Summary


Variables and constants are the building blocks of any programming language. In this lesson you learned the part they play in JavaScript, how you declare and assign values to them, how to name your variables correctly, and you also had a taste of using variables in JavaScript.

In the next lesson you're going to learn about JavaScript operators and do more and more practice with variables.

Take a break and get ready for lesson 5.

Post a Comment

70 Comments
  1. order diazepam diazepam online no prescription - diazepam dose for muscle spasm

    ReplyDelete
  2. buy xanax online ambien xanax and alcohol together - xanax schedule ii drug

    ReplyDelete
  3. buy valium online valium questions - diazepam (valium) synthesis

    ReplyDelete
  4. buy ativan ativan dosage ems - buy ativan united states

    ReplyDelete
  5. buy ativan online ativan restless leg syndrome - generic lorazepam vs ativan

    ReplyDelete
  6. ativan sale ativan much get high - ativan and alcohol bluelight

    ReplyDelete
  7. ativan online pharmacy how long does ativan withdrawal last - ativan buy

    ReplyDelete
  8. cheap ativan online order ativan online no prescription - ativan side effects sleep

    ReplyDelete
  9. ativan drug ativan vertigo - buy generic lorazepam

    ReplyDelete
  10. generic xanax buy xanax online with paypal or money order - xanax bars effects erowid

    ReplyDelete
  11. buy soma online soma muscle relaxer erowid - info on the drug soma

    ReplyDelete
  12. valium online pharmacy what do generic valium pills look like - valium pills what are for

    ReplyDelete
  13. buy soma somanabolic muscle maximizer diet - carisoprodol maximum daily dosage

    ReplyDelete
  14. carisoprodol soma carisoprodol pregnancy - somanabolic muscle maximizer and all bonus programs free download

    ReplyDelete
  15. valium sale valium length of effects - valium helps anxiety

    ReplyDelete
  16. valium 10 mg cost valium cvs - cheap valium from india

    ReplyDelete
  17. Blogger: Network - Post a Comment buy generic soma online no prescription - generic soma no prescription http://www.emprendiendoideas.com/#generic-soma-no-prescription

    ReplyDelete
  18. Blogger: Network - Post a Comment cheap prednisone - cheap prednisone online http://www.ourdailybreadmarket.net/#cheap-prednisone-online

    ReplyDelete
  19. Blogger: Network - Post a Comment buy prednisolone - buy prednisolone online http://www.ourdailybreadmarket.net/#buy-prednisolone-online

    ReplyDelete
  20. Blogger: Network - Post a Comment generic soma - cheap soma no prescription http://www.emprendiendoideas.com/#cheap-soma-no-prescription

    ReplyDelete
  21. Blogger: Network - Post a Comment ventolin cost - ventolin for sale http://www.ventolinforsaleonline.com/#ventolin-for-sale

    ReplyDelete
  22. Blogger: Network - Post a Comment generic rimonabant - where can i buy acomplia online http://www.a6soft.com/#where-can-i-buy-acomplia-online

    ReplyDelete
  23. Blogger: Network - Post a Comment prednisone medication - prednisone no prescription http://www.ourdailybreadmarket.net/#prednisone-no-prescription

    ReplyDelete
  24. Hello, buy generic effexor - cheap effexor http://www.effexorcostonline.com/#cheap-effexor

    ReplyDelete
  25. How Has Medicine Changed acomplia online no prescription - order acomplia http://www.buydiscountedisotretinoin.net/#order-acomplia

    ReplyDelete
  26. Information About Medication Named Gabapentin buy acomplia rimonabant - cheap acomplia http://www.buydiscountedisotretinoin.net/#cheap-acomplia

    ReplyDelete
  27. Orlando Fl Drug Dealers acomplia uk - buy acomplia rimonabant http://www.buydiscountedisotretinoin.net/#buy-acomplia-rimonabant

    ReplyDelete
  28. Top Drug Rehab Clinic Virginia acomplia for sale - acomplia without prescription http://www.buydiscountedisotretinoin.net/#acomplia-without-prescription

    ReplyDelete
  29. Urinary Incontinence In Adults Drugs acomplia 20mg pills - rimonabant online http://www.buydiscountedisotretinoin.net/#rimonabant-online

    ReplyDelete
  30. Hello, cytotec pill - discount cytotec http://www.cytotecforlessonline.net/#discount-cytotec

    ReplyDelete
  31. advitleva propecia price - cheap propecia http://www.bestpricefinasteride.com/

    ReplyDelete
  32. dalsCleax acomplia 20mg - buy acomplia online no prescription http://www.acompliadietpillcheap.com/#buy-acomplia-online-no-prescription

    ReplyDelete
  33. How Drugs Affect Your Life meridia diet pills for sale - meridia pills online http://www.meridiaonlineorder.net/#meridia-pills-online , [url=http://www.meridiaonlineorder.net/#meridia-without-prescription ]meridia without prescription [/url]

    ReplyDelete
  34. Atlanta Center For Reproductive Medicine meridia cost - where to buy meridia diet pills http://www.meridiaonlineorder.net/#where-to-buy-meridia-diet-pills , [url=http://www.meridiaonlineorder.net/#meridia-diet-pills-without-prescription ]meridia diet pills without prescription [/url]

    ReplyDelete
  35. 2, propecia online - cheap finasteride http://www.propeciagenericforsale.com/#order-propecia-online , [url=http://www.propeciagenericforsale.com/#propecia-online-pharmacy ]generic finasteride [/url]

    ReplyDelete
  36. [url=http://vtyupdr.com]SCpgrvNPKkCXTows[/url] , zILVeIOKKsKwZ - http://pyfnknfrtw.com

    ReplyDelete
  37. rvb prozac online - buy prozac http://www.prozacforsaleonline.net/#buy-prozac , [url=http://www.prozacforsaleonline.net/#prozac-cost ]prozac cost [/url]

    ReplyDelete
  38. tby buy furosemide online no prescription - lasix medication http://www.lasixforsaleonline.net/#lasix-medication , [url=http://www.lasixforsaleonline.net/#lasix-pills ]lasix pills [/url]

    ReplyDelete
  39. x90, Maxalt No Prescription - maxalt online pharmacy http://www.maxaltonlinerx.net/maxalt-online-pharmacy.html#Rizatriptan-Prescription, [url=http://www.maxaltonlinerx.net/maxalt-online-pharmacy.html#Maxalt-Pills]Rizatriptan Prescription[/url]

    ReplyDelete
  40. 6, imitrex for sale - generic imitrex cost http://www.imitrexonlinebuy.com/#buy-sumatripan, [url=http://www.imitrexonlinebuy.com/#sumatriptan-without-prescription]imitrex for sale[/url]

    ReplyDelete
  41. ooo!!! Topamax Cost - topiramate price http://www.topamaxbestonline.net/#generic-topiramate, [url=http://www.topamaxbestonline.net/#generic-topiramate]Buy Topamax[/url]

    ReplyDelete
  42. 2013 cheap wellbutrin - zyban without prescription http://www.wellbutrinforsaleonline.net/#order-zyban, [url=http://www.wellbutrinforsaleonline.net/#zyban-sale]zyban sale[/url]

    ReplyDelete
  43. g, isotretinoin without prescription - buy cheap accutane http://www.freeyogablog.com/#buy-cheap-accutane , [url=http://www.freeyogablog.com/#cheap-isotretinoin-online ]cheap isotretinoin online [/url]

    ReplyDelete
  44. ny, generic isotretinoin - buy accutane online no prescription http://www.freeyogablog.com/#buy-accutane-online-no-prescription , [url=http://www.freeyogablog.com/#isotretinoin-no-prescription ]isotretinoin no prescription [/url]

    ReplyDelete
  45. ny, imitrex pills - generic imitrex cost http://itrafficgeneration.com/#generic-imitrex-cost , [url=http://itrafficgeneration.com/#generic-imitrex-without-prescription ]generic imitrex without prescription [/url]

    ReplyDelete
  46. c, neurontin for sale - purchase neurontin http://www.neurontinonlinesales.net/, [url=http://www.neurontinonlinesales.net/]neurontin online[/url]

    ReplyDelete
  47. Hi, ambien price - purchase ambien no prescription http://www.ambienwheretobuy.com/, [url=http://www.ambienwheretobuy.com/]generic ambien cr [/url]

    ReplyDelete
  48. 4, cheap modafinil - generic provigil online http://www.energyofprovigil.net/#provigil-online-pharmacy, [url=http://www.energyofprovigil.net/#provigil-for-sale]cheap modafinil[/url]

    ReplyDelete
  49. 4, buy strattera atomoxetine - strattera cost http://www.stratterafastonline.net/, [url=http://www.stratterafastonline.net/]generic strattera [/url]

    ReplyDelete
  50. 2, [url=http://www.nexiumonlinefaq.net/]Generic Nexium[/url] - Buy Nexium - generic nexium no prescription http://www.nexiumonlinefaq.net/.

    ReplyDelete
  51. cheap imitrex - imitrex no prescription needed http://www.imitrexbenefits.net/, [url=http://www.imitrexbenefits.net/]generic sumatriptan[/url]

    ReplyDelete
  52. buy imitrex - imitrex online http://www.imitrexbenefits.net/, [url=http://www.imitrexbenefits.net/]cheap imitrex[/url]

    ReplyDelete
  53. 6, [url=http://www.nexiumpricewatch.net/] Esomeprazole Online [/url] - Cheap Nexium - nexium online no prescription http://www.nexiumpricewatch.net/ .

    ReplyDelete
  54. 5, [url=http://www.costofeffexor.net/]Generic Effexor[/url] - Generic Effexor - buy effexor online http://www.costofeffexor.net/ .

    ReplyDelete
  55. 6, [url=http://www.nexiumpricewatch.net/] Buy Nexium [/url] - Buy Nexium - buy nexium no prescription http://www.nexiumpricewatch.net/ .

    ReplyDelete
  56. 5, [url=http://www.isotretinoinonlinerx.net/] Accutane Cost[/url] - Cheap Accutane - accutane price http://www.isotretinoinonlinerx.net/ .

    ReplyDelete
  57. 6, [url=http://www.nexiumpricewatch.net/] Nexium Price [/url] - Generic Nexium - buy nexium no prescription http://www.nexiumpricewatch.net/ .

    ReplyDelete
  58. 6, [url=http://www.cheapzoloftrx.net/]Buy Zoloft [/url] - Zoloft Cost - buy sertraline no prescription http://www.cheapzoloftrx.net/ .

    ReplyDelete
  59. 11, [url=http://www.encuentrocubano.com/]Order Fluoxetine [/url] - Cheap Prozac - generic prozac no prescription http://www.encuentrocubano.com/ .

    ReplyDelete
  60. Big savings with acai berry PlusIn this time of year
    by selecting snowman candles, snowflake ornaments
    or a beautiful blue gel candle with a snowflake on it.

    Moussa's children stare at me silently, their mouths open, with uncertain expressions on their faces.

    Here is my web page :: Acai berry select weight Loss

    ReplyDelete
  61. 14, [url=http://www.cymbaltaonlineorder.com/]Order Cymbalta Online[/url] - Order Cymbalta Online - low cost cymbalta http://www.cymbaltaonlineorder.com/ .

    ReplyDelete
  62. 17, [url=http://www.terrazadelnorte.com/] Order Soma [/url] - Cheap Carisoprodol - soma without rx http://www.terrazadelnorte.com/ .

    ReplyDelete
  63. Your curгent post оffers confirmed necessаry to uѕ.
    Ӏt’s quitе еducationаl
    and уou're simply clearly quite experienced of this type. You have exposed our eye to various views on this kind of subject matter together with interesting and solid content.

    Also visit my web site - wiki-paesaggio.arc.uniroma1.it
    Here is my web-site - buy levitra

    ReplyDelete
  64. UGG Australia has produced some unique and fun types in boots for ladies - Classic Stripe
    UGG Boots really are a perfect illustration of this.
    ì (IE: sand, chestnut, chocolate, black) UGG boots. And utilization of
    the preserving stratum inside knock-off might be a easy preventative pelage - not the true authenticated guy who are able
    to conflict users; the production is her toes
    when her vernacular users of sea boots check inside the U.


    Here is my page: コーチ 財布

    ReplyDelete
  65. Yοur own report fеaturеs verifіed beneficial to me.
    It’s really educаtional and yοu arе naturally quite κnowledgеable of thiѕ
    type. Υou hаve got рοpped my eуe
    to various opinіon of this subjеct using intriguing,
    notable and solid articles.
    My blog post - buy viagra

    ReplyDelete
  66. Bereits seit mehrегen Јahren
    gilt Viagra als еines dеr bеkannteѕten Оrgaѕmusmіttel fֳ¼r Нeгren sowie dаѕ aus gutem Grunԁ, denn dаs Orgaѕmusproduκt Viagга іst abѕolut wirksаm.
    Orіginal cialis гezeptfrei
    Feel free to visit my web blog cialis

    ReplyDelete
  67. Youг currеnt write-up has сonfіrmed benеficіal to me.
    It’s extгemеly іnfοrmаtive
    аnd уou're naturally quite well-informed of this type. You have exposed our eye to numerous views on this specific matter with intriguing, notable and solid written content.

    my website: Cialis

    ReplyDelete
  68. I am sure this post has touched all the internet people, its really really nice piece of writing on building up new blog.

    ReplyDelete
* Please Don't Spam Here. All the Comments are Reviewed by Admin.