Search code examples
javascriptvariable-assignmentstring-lengthglobal-object

Stuck. New to JS. Trying to figure this out since hours


I can't solve exercise three and four. I would be very pleased to get some help. Thank you in advance!

function exerciseThree(str){
  // In this exercise, you will be given a variable, it will be called: str
  // On the next line create a variable called 'length' and using the length property assign the new variable to the length of str


  // Please write your answer in the line above.
  return length; 
}

function exerciseFour(num1){
  // In this exercise, you will be given a variable, it will be called: num1
  // On the next line create a variable called 'rounded'. Call the Math global object's round method, passing it num1, and assign it to the rounded variable.
  var num1 = rounded;
  math.round (num1); 

  // Please write your answer in the line above.
  return rounded;
}

Solution

  • These exercises are trying to teach you how to declare variables and how to assign values to them.

    Variables are like little containers that hold values for you. For example, I can make a little container to hold your name. And since one of the ways to declare a variable in JavaScript is to use the var keyword, I could write something as following:

    var name = "Sevr";
    

    I made a container with var keyword and named it name. This name container now holds your name which is Sevr. Instead of typing Sevr over and over again you can now type Name over and over. But, this doesn't make much difference. Sevr and name both contain same number of characters. It makes more sense to have your variables contain information that you don't want to type over and over again.

    So exercise three wants you to declare a variable named length and make it hold the length of any string that it is provided with.

    function exerciseThree(str) {
            var length = str.length
            return length;
    }
    

    This function above takes a string, you make a variable named length that contains the length of that string.

    Now if we pass it any string it will tell us what length they are. If we pass it your name Sevr and name and we will see that they both return 4:

    exerciseThree("name") // 4
    exerciseThree("Sevr") // 4
    

    On the fourth exercise, the concept is the same. The exercise wants to teach you that you can make a simple variable name that can hold on to some complex value for you. This time it wants you to declare variable named rounded that holds on to the rounded value of a number.

    function exerciseFour(num1) {
        var rounded = Math.round(num1)
        return rounded;
    }
    

    And, now if you pass a number with decimals to this function it will round it for you.

    exerciseFour(4.5) // 5