Beginner Attempting to Create a JavaScript Age Calculator

As a beginner in self-learning, I've recently started diving into the world of JavaScript. Currently, I am facing a challenge with an assignment from an online code camp that I just can't seem to figure out. Despite grasping the basics, I struggle to execute it effectively. Can anyone offer assistance?

The specific question is provided in the attached image.

Here is a snippet of my existing code:

function ageCalculator(name, yearOfBirth, currentYear) {
  var age = currentYear - yearOfBirth;
  return (name + "is" + age + "years old.");
  console.log(ageCalculator("Miranda", 1983, 2015));
}

Your help would be greatly appreciated. Thank you!

Answer №1

It appears that you are calling the function ageCalculator right after the return statement, which means it will not be executed.

To fix this, simply move the function call outside of the return statement like so:

function ageCalculator(name, yearOfBirth, currentYear) {
  var age = currentYear - yearOfBirth;
  return (name + " is " + age + " years old.");  
}

console.log(ageCalculator("Miranda", 1983, 2015));

Answer №2

Make sure to invoke the function after declaring it.

function calculateAge(name, birthYear, currentYear) {
    var age = currentYear - birthYear;
    return (name + " is " + age + " years old.");
}
    
console.log(calculateAge("Ella", 1990, 2022));

Answer №3

Every time you use the return statement, the function will halt immediately: it won't ever reach your console.log in its current state. Remember to execute console.log and call the function itself outside of the function definition to prevent an infinite recursive loop.

Additionally, ensure proper indentation:

function ageCalculator(name, yearOfBirth, currentYear) {
    var age = currentYear - yearOfBirth;
    return (name + " is " + age + " years old.");
}
console.log(ageCalculator("Miranda", 1983, 2015));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include dropdown lists for selecting the year, month, and day on a web page

Is there a way to implement a dropdown style date selector that dynamically updates the number of days based on the selected year and month using JavaScript? For example, February 2008 has 29 days, April has 30 days, and June has 31 days. Any suggestions ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Tips for limiting the .click function to only the initial image in order to prevent loading all images within the container

I am facing a situation where multiple images are being returned into a specific div, which is working as intended. <div class="go" id="container"></div> Upon clicking on an image, it is loaded into a modal popup. However, instead of capturin ...

Adding classes to a div in a sequential animation using jQuery: A step-by-step guide

I'm aiming to create an animated effect using jQuery that replicates the motion in this GIF. I experimented with CSS3 animation keyframes, but the result was not as clean and polished as I would like. If there is a simpler way to achieve this effect u ...

Icon that can be clicked in a div container

Is there a way to prevent the div click event from being triggered when clicking on ion-icon? <div(click)="goNext()"> <ion-icon name="close-circle-outline" size="large" (click)="dissmiss()"></io ...

jQuery conceal input field after it has been displayed

I've created an HTML form with two different sections for search purposes. The first section displays basic fields, and by clicking on "Advanced Search" (in my case, "Расширенный поиск"), additional fields are revealed. Everything work ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...

Is the ng-style not displaying the background image with the interpolated value?

I have been attempting to update the background image of a div using angular ng-style. Below is the code I am working with: <div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div> However, ...

ajaxStart event does not trigger when making an Ajax POST request

My ajaxStart event functions properly for ajax loads, but it does not work at all when I do a POST request. The following code is consistently rendered on all pages: $(document).ajaxComplete(function () { hideIcon(); if (stepState !== &a ...

Creating a Kendo UI grid within a Kendo UI window and utilizing Knockout JS bindings

I'm encountering an unusual issue while working with Kendo UI and Knockout JS libraries. When attempting to display a kendo grid within a kendo window, the rows inside the grid are being duplicated. Below is a snippet of the code I'm using: JS: ...

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...

What is the best way to pass an email as a Laravel parameter within a function using Angular?

I'm currently working on a feature that allows users to delete their account only if the input field matches their email address. However, I encountered an error: Error: $parse:lexerr Lexer Error when attempting to set this up. Here is my HTML code: ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Cross domain tracking pixel implemented using ASP.NET, jQuery, and AJAX technology

Currently, I have a page tracking system that uses $.post(PAIRS-DATA) in JavaScript to send collected information back to the server and load as a tracking pixel. finally { //tracking pixel Response.ContentType = "i ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

The feature of webpack that enables it to monitor node modules for hot reloading is currently malfunctioning

Using npm link in our primary application to point to the submodules packages has been successful. I am interested in adding a new feature that involves reloading the app whenever the references placed through npm link are updated, as there may be changes ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

What is the best way to automatically select a checkbox when using ng-repeat on page

I'm looking to automatically check an input checkbox when the page loads, and if it's checked, subtract its value from the total. How can I tackle this issue? Here's the HTML snippet: <p>{{vm.TOTAL VALUE}}</p> <tr ng-repeat= ...